[X86] Don't custom-lower vNi32 uint_to_fp when unsafe-fp-math.
[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/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117   }
118
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168       // f32/f64 are legal, f80 is custom.
169       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
170     else
171       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173   } else if (!Subtarget->useSoftFloat()) {
174     // We have an algorithm for SSE2->double, and we turn this into a
175     // 64-bit FILD followed by conditional FADD for other targets.
176     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
177     // We have an algorithm for SSE2, and we turn this into a 64-bit
178     // FILD or VCVTUSI2SS/SD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
180   }
181
182   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
183   // this operation.
184   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
186
187   if (!Subtarget->useSoftFloat()) {
188     // SSE has no i16 to fp conversion, only i32
189     if (X86ScalarSSEf32) {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
191       // f32 and f64 cases are Legal, f80 case is not
192       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
193     } else {
194       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     }
197   } else {
198     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
200   }
201
202   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
203   // are Legal, f80 is custom lowered.
204   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
205   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
206
207   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
208   // this operation.
209   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
210   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
211
212   if (X86ScalarSSEf32) {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
214     // f32 and f64 cases are Legal, f80 case is not
215     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
216   } else {
217     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
218     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
219   }
220
221   // Handle FP_TO_UINT by promoting the destination to a larger signed
222   // conversion.
223   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
224   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
225   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
226
227   if (Subtarget->is64Bit()) {
228     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
229       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
231       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
232     } else {
233       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
234       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
235     }
236   } else if (!Subtarget->useSoftFloat()) {
237     // Since AVX is a superset of SSE3, only check for SSE here.
238     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
239       // Expand FP_TO_UINT into a select.
240       // FIXME: We would like to use a Custom expander here eventually to do
241       // the optimal thing for SSE vs. the default expansion in the legalizer.
242       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
243     else
244       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248
249     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
250   }
251
252   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253   if (!X86ScalarSSEf64) {
254     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
255     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
256     if (Subtarget->is64Bit()) {
257       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
258       // Without SSE, i64->f64 goes through memory.
259       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
260     }
261   }
262
263   // Scalar integer divide and remainder are lowered to use operations that
264   // produce two results, to match the available instructions. This exposes
265   // the two-result form to trivial CSE, which is able to combine x/y and x%y
266   // into a single instruction.
267   //
268   // Scalar integer multiply-high is also lowered to use two-result
269   // operations, to match the available instructions. However, plain multiply
270   // (low) operations are left as Legal, as there are single-result
271   // instructions for this in x86. Using the two-result multiply instructions
272   // when both high and low results are needed must be arranged by dagcombine.
273   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
274     MVT VT = IntVTs[i];
275     setOperationAction(ISD::MULHS, VT, Expand);
276     setOperationAction(ISD::MULHU, VT, Expand);
277     setOperationAction(ISD::SDIV, VT, Expand);
278     setOperationAction(ISD::UDIV, VT, Expand);
279     setOperationAction(ISD::SREM, VT, Expand);
280     setOperationAction(ISD::UREM, VT, Expand);
281
282     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283     setOperationAction(ISD::ADDC, VT, Custom);
284     setOperationAction(ISD::ADDE, VT, Custom);
285     setOperationAction(ISD::SUBC, VT, Custom);
286     setOperationAction(ISD::SUBE, VT, Custom);
287   }
288
289   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
290   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
291   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
305   if (Subtarget->is64Bit())
306     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
308   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
309   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
310   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
311
312   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
313     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
314     // is. We should promote the value to 64-bits to solve this.
315     // This is what the CRT headers do - `fmodf` is an inline header
316     // function casting to f64 and calling `fmod`.
317     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
318   } else {
319     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
320   }
321
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->isTarget64BitLP64()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit()) {
502     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
503     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
504   } else {
505     // TargetInfo::CharPtrBuiltinVaList
506     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
507     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
508   }
509
510   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
511   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
512
513   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
514
515   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
517   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
518
519   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
520     // f32 and f64 use SSE.
521     // Set up the FP register classes.
522     addRegisterClass(MVT::f32, &X86::FR32RegClass);
523     addRegisterClass(MVT::f64, &X86::FR64RegClass);
524
525     // Use ANDPD to simulate FABS.
526     setOperationAction(ISD::FABS , MVT::f64, Custom);
527     setOperationAction(ISD::FABS , MVT::f32, Custom);
528
529     // Use XORP to simulate FNEG.
530     setOperationAction(ISD::FNEG , MVT::f64, Custom);
531     setOperationAction(ISD::FNEG , MVT::f32, Custom);
532
533     // Use ANDPD and ORPD to simulate FCOPYSIGN.
534     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
535     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
536
537     // Lower this to FGETSIGNx86 plus an AND.
538     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
539     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
540
541     // We don't support sin/cos/fmod
542     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
545     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
546     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
547     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
548
549     // Expand FP immediates into loads from the stack, except for the special
550     // cases we handle.
551     addLegalFPImmediate(APFloat(+0.0)); // xorpd
552     addLegalFPImmediate(APFloat(+0.0f)); // xorps
553   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
554     // Use SSE for f32, x87 for f64.
555     // Set up the FP register classes.
556     addRegisterClass(MVT::f32, &X86::FR32RegClass);
557     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
558
559     // Use ANDPS to simulate FABS.
560     setOperationAction(ISD::FABS , MVT::f32, Custom);
561
562     // Use XORP to simulate FNEG.
563     setOperationAction(ISD::FNEG , MVT::f32, Custom);
564
565     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
566
567     // Use ANDPS and ORPS to simulate FCOPYSIGN.
568     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
569     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
570
571     // We don't support sin/cos/fmod
572     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
573     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
574     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
575
576     // Special cases we handle for FP constants.
577     addLegalFPImmediate(APFloat(+0.0f)); // xorps
578     addLegalFPImmediate(APFloat(+0.0)); // FLD0
579     addLegalFPImmediate(APFloat(+1.0)); // FLD1
580     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
581     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
582
583     if (!TM.Options.UnsafeFPMath) {
584       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
585       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
586       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
587     }
588   } else if (!Subtarget->useSoftFloat()) {
589     // f32 and f64 in x87.
590     // Set up the FP register classes.
591     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
592     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
593
594     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
595     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
596     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
598
599     if (!TM.Options.UnsafeFPMath) {
600       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
601       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
602       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
604       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
606     }
607     addLegalFPImmediate(APFloat(+0.0)); // FLD0
608     addLegalFPImmediate(APFloat(+1.0)); // FLD1
609     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
615   }
616
617   // We don't support FMA.
618   setOperationAction(ISD::FMA, MVT::f64, Expand);
619   setOperationAction(ISD::FMA, MVT::f32, Expand);
620
621   // Long double always uses X87.
622   if (!Subtarget->useSoftFloat()) {
623     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
624     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
626     {
627       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
628       addLegalFPImmediate(TmpFlt);  // FLD0
629       TmpFlt.changeSign();
630       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
631
632       bool ignored;
633       APFloat TmpFlt2(+1.0);
634       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
635                       &ignored);
636       addLegalFPImmediate(TmpFlt2);  // FLD1
637       TmpFlt2.changeSign();
638       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
639     }
640
641     if (!TM.Options.UnsafeFPMath) {
642       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
643       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
644       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
645     }
646
647     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
648     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
649     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
650     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
651     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
652     setOperationAction(ISD::FMA, MVT::f80, Expand);
653   }
654
655   // Always use a library call for pow.
656   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
657   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
659
660   setOperationAction(ISD::FLOG, MVT::f80, Expand);
661   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
663   setOperationAction(ISD::FEXP, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
665   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
666   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
667
668   // First set operation action for all vector types to either promote
669   // (for widening) or expand (for scalarization). Then we will selectively
670   // turn on ones that can be effectively codegen'd.
671   for (MVT VT : MVT::vector_valuetypes()) {
672     setOperationAction(ISD::ADD , VT, Expand);
673     setOperationAction(ISD::SUB , VT, Expand);
674     setOperationAction(ISD::FADD, VT, Expand);
675     setOperationAction(ISD::FNEG, VT, Expand);
676     setOperationAction(ISD::FSUB, VT, Expand);
677     setOperationAction(ISD::MUL , VT, Expand);
678     setOperationAction(ISD::FMUL, VT, Expand);
679     setOperationAction(ISD::SDIV, VT, Expand);
680     setOperationAction(ISD::UDIV, VT, Expand);
681     setOperationAction(ISD::FDIV, VT, Expand);
682     setOperationAction(ISD::SREM, VT, Expand);
683     setOperationAction(ISD::UREM, VT, Expand);
684     setOperationAction(ISD::LOAD, VT, Expand);
685     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
686     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
687     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
688     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
689     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::FABS, VT, Expand);
691     setOperationAction(ISD::FSIN, VT, Expand);
692     setOperationAction(ISD::FSINCOS, VT, Expand);
693     setOperationAction(ISD::FCOS, VT, Expand);
694     setOperationAction(ISD::FSINCOS, VT, Expand);
695     setOperationAction(ISD::FREM, VT, Expand);
696     setOperationAction(ISD::FMA,  VT, Expand);
697     setOperationAction(ISD::FPOWI, VT, Expand);
698     setOperationAction(ISD::FSQRT, VT, Expand);
699     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
700     setOperationAction(ISD::FFLOOR, VT, Expand);
701     setOperationAction(ISD::FCEIL, VT, Expand);
702     setOperationAction(ISD::FTRUNC, VT, Expand);
703     setOperationAction(ISD::FRINT, VT, Expand);
704     setOperationAction(ISD::FNEARBYINT, VT, Expand);
705     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
706     setOperationAction(ISD::MULHS, VT, Expand);
707     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
708     setOperationAction(ISD::MULHU, VT, Expand);
709     setOperationAction(ISD::SDIVREM, VT, Expand);
710     setOperationAction(ISD::UDIVREM, VT, Expand);
711     setOperationAction(ISD::FPOW, VT, Expand);
712     setOperationAction(ISD::CTPOP, VT, Expand);
713     setOperationAction(ISD::CTTZ, VT, Expand);
714     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
715     setOperationAction(ISD::CTLZ, VT, Expand);
716     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
717     setOperationAction(ISD::SHL, VT, Expand);
718     setOperationAction(ISD::SRA, VT, Expand);
719     setOperationAction(ISD::SRL, VT, Expand);
720     setOperationAction(ISD::ROTL, VT, Expand);
721     setOperationAction(ISD::ROTR, VT, Expand);
722     setOperationAction(ISD::BSWAP, VT, Expand);
723     setOperationAction(ISD::SETCC, VT, Expand);
724     setOperationAction(ISD::FLOG, VT, Expand);
725     setOperationAction(ISD::FLOG2, VT, Expand);
726     setOperationAction(ISD::FLOG10, VT, Expand);
727     setOperationAction(ISD::FEXP, VT, Expand);
728     setOperationAction(ISD::FEXP2, VT, Expand);
729     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
730     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
731     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
732     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
734     setOperationAction(ISD::TRUNCATE, VT, Expand);
735     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
736     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
737     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
738     setOperationAction(ISD::VSELECT, VT, Expand);
739     setOperationAction(ISD::SELECT_CC, VT, Expand);
740     for (MVT InnerVT : MVT::vector_valuetypes()) {
741       setTruncStoreAction(InnerVT, VT, Expand);
742
743       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
744       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
745
746       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
747       // types, we have to deal with them whether we ask for Expansion or not.
748       // Setting Expand causes its own optimisation problems though, so leave
749       // them legal.
750       if (VT.getVectorElementType() == MVT::i1)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752
753       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
754       // split/scalarized right now.
755       if (VT.getVectorElementType() == MVT::f16)
756         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
757     }
758   }
759
760   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
761   // with -msoft-float, disable use of MMX as well.
762   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
763     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
764     // No operations on x86mmx supported, everything uses intrinsics.
765   }
766
767   // MMX-sized vectors (other than x86mmx) are expected to be expanded
768   // into smaller operations.
769   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
770     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
771     setOperationAction(ISD::AND,                MMXTy,      Expand);
772     setOperationAction(ISD::OR,                 MMXTy,      Expand);
773     setOperationAction(ISD::XOR,                MMXTy,      Expand);
774     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
775     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
776     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
777   }
778   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
779
780   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
781     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
782
783     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
788     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
789     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
790     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
791     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
792     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
793     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
794     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
795     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
796     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
797   }
798
799   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
800     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
801
802     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
803     // registers cannot be used even for integer operations.
804     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
805     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
806     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
807     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
808
809     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
810     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
811     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
812     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
813     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
814     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
815     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
816     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
817     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
819     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
820     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
821     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
822     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
823     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
825     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
830     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
831     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
834     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
835     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
836     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
837
838     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
839     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
840     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
841     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
842
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
844     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
848
849     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
850     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
851     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
852     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
853
854     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
855     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
856     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
857     // ISD::CTTZ v2i64 - scalarization is faster.
858     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
861     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
862
863     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
864     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
865       MVT VT = (MVT::SimpleValueType)i;
866       // Do not attempt to custom lower non-power-of-2 vectors
867       if (!isPowerOf2_32(VT.getVectorNumElements()))
868         continue;
869       // Do not attempt to custom lower non-128-bit vectors
870       if (!VT.is128BitVector())
871         continue;
872       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
873       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
874       setOperationAction(ISD::VSELECT,            VT, Custom);
875       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
876     }
877
878     // We support custom legalizing of sext and anyext loads for specific
879     // memory vector types which we can load as a scalar (or sequence of
880     // scalars) and extend in-register to a legal 128-bit vector type. For sext
881     // loads these must work with a single scalar load.
882     for (MVT VT : MVT::integer_vector_valuetypes()) {
883       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
884       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
885       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
886       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
887       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
888       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
889       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
890       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
891       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
892     }
893
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
895     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
897     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
898     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
899     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
900     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
901     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
902
903     if (Subtarget->is64Bit()) {
904       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
906     }
907
908     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910       MVT VT = (MVT::SimpleValueType)i;
911
912       // Do not attempt to promote non-128-bit vectors
913       if (!VT.is128BitVector())
914         continue;
915
916       setOperationAction(ISD::AND,    VT, Promote);
917       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
918       setOperationAction(ISD::OR,     VT, Promote);
919       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
920       setOperationAction(ISD::XOR,    VT, Promote);
921       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
922       setOperationAction(ISD::LOAD,   VT, Promote);
923       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
924       setOperationAction(ISD::SELECT, VT, Promote);
925       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
926     }
927
928     // Custom lower v2i64 and v2f64 selects.
929     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
930     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
931     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
932     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
933
934     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
935     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
936
937     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
938
939     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
940     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
941     // As there is no 64-bit GPR available, we need build a special custom
942     // sequence to convert from v2i32 to v2f32.
943     if (!Subtarget->is64Bit())
944       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
945
946     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
947     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
948
949     for (MVT VT : MVT::fp_vector_valuetypes())
950       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
951
952     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
953     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
954     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
955   }
956
957   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
960       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
961       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
962       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
963       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
964     }
965
966     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
967     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
968     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
969     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
970     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
971     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
972     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
973     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
974
975     // FIXME: Do we need to handle scalar-to-vector here?
976     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
977
978     // We directly match byte blends in the backend as they match the VSELECT
979     // condition form.
980     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
981
982     // SSE41 brings specific instructions for doing vector sign extend even in
983     // cases where we don't have SRA.
984     for (MVT VT : MVT::integer_vector_valuetypes()) {
985       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
988     }
989
990     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
997
998     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1004
1005     // i8 and i16 vectors are custom because the source register and source
1006     // source memory operand types are not the same width.  f32 vectors are
1007     // custom since the immediate controlling the insert encodes additional
1008     // information.
1009     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1010     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1013
1014     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1018
1019     // FIXME: these should be Legal, but that's only for the case where
1020     // the index is constant.  For now custom expand to deal with that.
1021     if (Subtarget->is64Bit()) {
1022       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1023       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1024     }
1025   }
1026
1027   if (Subtarget->hasSSE2()) {
1028     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1031
1032     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1033     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1034
1035     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1036     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1037
1038     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1039     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1040
1041     // In the customized shift lowering, the legal cases in AVX2 will be
1042     // recognized.
1043     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1044     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1045
1046     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1047     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1048
1049     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1050     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1051   }
1052
1053   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1054     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1055     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1056     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1057     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1059     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1060
1061     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1062     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1063     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1064
1065     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1066     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1069     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1070     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1071     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1072     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1073     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1074     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1075     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1076     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1077
1078     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1079     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1082     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1083     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1084     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1085     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1086     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1087     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1088     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1089     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1090
1091     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1092     // even though v8i16 is a legal type.
1093     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1094     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1095     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1096
1097     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1098     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1099     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1100
1101     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1102     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1103
1104     for (MVT VT : MVT::fp_vector_valuetypes())
1105       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1106
1107     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1114     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1115
1116     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1117     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1118     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1119     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1120
1121     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1122     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1123     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1124
1125     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1126     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1127     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1128     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1129     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1130     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1131     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1132     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1133     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1134     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1135     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1136     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1137
1138     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1139     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1140     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1141     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1142
1143     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1144     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1145     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1146     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1147     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1148     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1149     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1150     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1151
1152     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1153       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1154       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1155       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1156       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1157       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1158       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1159     }
1160
1161     if (Subtarget->hasInt256()) {
1162       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1163       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1164       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1165       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1166
1167       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1168       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1169       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1170       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1171
1172       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1173       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1174       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1175       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1176
1177       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1178       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1179       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1180       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1181
1182       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1183       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1184       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1185       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1186       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1187       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1188       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1189       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1190       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1191       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1192       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1193       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1194
1195       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1196       // when we have a 256bit-wide blend with immediate.
1197       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1198
1199       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1201       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1202       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1203       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1204       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1205       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1206
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1208       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1209       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1210       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1211       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1212       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1213     } else {
1214       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1215       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1216       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1217       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1218
1219       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1220       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1221       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1222       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1223
1224       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1227       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1228
1229       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1230       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1231       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1232       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1233       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1234       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1235       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1236       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1237       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1238       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1239       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1240       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1241     }
1242
1243     // In the customized shift lowering, the legal cases in AVX2 will be
1244     // recognized.
1245     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1246     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1247
1248     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1249     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1250
1251     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1253
1254     // Custom lower several nodes for 256-bit types.
1255     for (MVT VT : MVT::vector_valuetypes()) {
1256       if (VT.getScalarSizeInBits() >= 32) {
1257         setOperationAction(ISD::MLOAD,  VT, Legal);
1258         setOperationAction(ISD::MSTORE, VT, Legal);
1259       }
1260       // Extract subvector is special because the value type
1261       // (result) is 128-bit but the source is 256-bit wide.
1262       if (VT.is128BitVector()) {
1263         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1264       }
1265       // Do not attempt to custom lower other non-256-bit vectors
1266       if (!VT.is256BitVector())
1267         continue;
1268
1269       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1270       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1271       setOperationAction(ISD::VSELECT,            VT, Custom);
1272       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1273       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1275       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1276       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1277     }
1278
1279     if (Subtarget->hasInt256())
1280       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1281
1282     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284       MVT VT = (MVT::SimpleValueType)i;
1285
1286       // Do not attempt to promote non-256-bit vectors
1287       if (!VT.is256BitVector())
1288         continue;
1289
1290       setOperationAction(ISD::AND,    VT, Promote);
1291       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1292       setOperationAction(ISD::OR,     VT, Promote);
1293       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1294       setOperationAction(ISD::XOR,    VT, Promote);
1295       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1296       setOperationAction(ISD::LOAD,   VT, Promote);
1297       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1298       setOperationAction(ISD::SELECT, VT, Promote);
1299       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300     }
1301   }
1302
1303   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1304     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1308
1309     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1310     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1311     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1312
1313     for (MVT VT : MVT::fp_vector_valuetypes())
1314       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1315
1316     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1317     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1318     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1319     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1320     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1321     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1322     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1323     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1324     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1325     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1326     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1327     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1328
1329     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1330     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1331     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1332     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1333     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1334     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1335     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1336     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1337     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1340     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1341     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1342
1343     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1344     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1348     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1349
1350     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1356     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1357     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1358
1359     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1362     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1363     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1365     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1366     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1367     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1368     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1371     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1372     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1373     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1374     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1375
1376     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1377     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1378     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1379     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1380     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1381     if (Subtarget->hasVLX()){
1382       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1383       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1384       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1385       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1386       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1387
1388       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1389       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1390       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1391       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1392       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1393     }
1394     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1395     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1396     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1397     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1398     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1399     if (Subtarget->hasDQI()) {
1400       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1401       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1402
1403       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1404       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1405       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1406       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1407       if (Subtarget->hasVLX()) {
1408         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1409         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1410         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1411         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1412         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1413         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1414         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1415         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1416       }
1417     }
1418     if (Subtarget->hasVLX()) {
1419       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1420       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1421       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1422       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1423       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1424       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1425       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1426       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1427     }
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1434     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1438     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1439     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1440     if (Subtarget->hasDQI()) {
1441       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1442       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1443     }
1444     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1445     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1446     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1447     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1448     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1449     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1450     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1451     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1452     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1453     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1454
1455     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1456     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1457     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1458     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1460
1461     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1462     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1463
1464     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1465
1466     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1467     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1468     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1469     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1470     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1471     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1474     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1475     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1476     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1477
1478     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1479     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1480     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1481     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1482     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1483     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1484     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1485     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1486
1487     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1488     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1489
1490     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1491     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1492
1493     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1494
1495     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1496     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1497
1498     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1499     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1500
1501     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1502     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1503
1504     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1505     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1506     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1507     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1508     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1509     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1510
1511     if (Subtarget->hasCDI()) {
1512       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1513       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1514       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64, Legal);
1515       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1516
1517       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64, Custom);
1518       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1519     }
1520     if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1521       setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1522       setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1523       setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1524       setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1525       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1526       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1527       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1528       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1529
1530       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1531       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1532       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1533       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1534     }
1535     if (Subtarget->hasDQI()) {
1536       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1537       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1538       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1539     }
1540     // Custom lower several nodes.
1541     for (MVT VT : MVT::vector_valuetypes()) {
1542       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1543       if (EltSize == 1) {
1544         setOperationAction(ISD::AND, VT, Legal);
1545         setOperationAction(ISD::OR,  VT, Legal);
1546         setOperationAction(ISD::XOR,  VT, Legal);
1547       }
1548       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1549         setOperationAction(ISD::MGATHER,  VT, Custom);
1550         setOperationAction(ISD::MSCATTER, VT, Custom);
1551       }
1552       // Extract subvector is special because the value type
1553       // (result) is 256/128-bit but the source is 512-bit wide.
1554       if (VT.is128BitVector() || VT.is256BitVector()) {
1555         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1556       }
1557       if (VT.getVectorElementType() == MVT::i1)
1558         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1559
1560       // Do not attempt to custom lower other non-512-bit vectors
1561       if (!VT.is512BitVector())
1562         continue;
1563
1564       if (EltSize >= 32) {
1565         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1566         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1567         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1568         setOperationAction(ISD::VSELECT,             VT, Legal);
1569         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1570         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1571         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1572         setOperationAction(ISD::MLOAD,               VT, Legal);
1573         setOperationAction(ISD::MSTORE,              VT, Legal);
1574       }
1575     }
1576     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1577       MVT VT = (MVT::SimpleValueType)i;
1578
1579       // Do not attempt to promote non-512-bit vectors.
1580       if (!VT.is512BitVector())
1581         continue;
1582
1583       setOperationAction(ISD::SELECT, VT, Promote);
1584       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1585     }
1586   }// has  AVX-512
1587
1588   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1589     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1590     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1591
1592     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1593     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1594
1595     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1596     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1597     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1598     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1599     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1600     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1601     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1602     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1603     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1604     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1605     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1606     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1607     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1608     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1609     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1610     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1611     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1612     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1613     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1614     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1615     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1616     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1617     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1618     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1619     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1620     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1621     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1622     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1623     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1624     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1625     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1626     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1627     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1628
1629     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1630     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1631     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1632     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1633     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1634     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1635     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1636     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1637
1638     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1639     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1640     if (Subtarget->hasVLX())
1641       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1642
1643     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1644       const MVT VT = (MVT::SimpleValueType)i;
1645
1646       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1647
1648       // Do not attempt to promote non-512-bit vectors.
1649       if (!VT.is512BitVector())
1650         continue;
1651
1652       if (EltSize < 32) {
1653         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1654         setOperationAction(ISD::VSELECT,             VT, Legal);
1655       }
1656     }
1657   }
1658
1659   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1660     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1661     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1662
1663     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1664     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1665     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1666     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1667     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1668     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1669     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1670     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1671     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1672     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1673     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1674     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1675
1676     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1677     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1678     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1679     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1680     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1681     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1682     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1683     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1684
1685     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1686     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1687     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1688     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1689     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1690     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1691     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1692     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1693   }
1694
1695   // We want to custom lower some of our intrinsics.
1696   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1697   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1698   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1699   if (!Subtarget->is64Bit())
1700     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1701
1702   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1703   // handle type legalization for these operations here.
1704   //
1705   // FIXME: We really should do custom legalization for addition and
1706   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1707   // than generic legalization for 64-bit multiplication-with-overflow, though.
1708   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1709     // Add/Sub/Mul with overflow operations are custom lowered.
1710     MVT VT = IntVTs[i];
1711     setOperationAction(ISD::SADDO, VT, Custom);
1712     setOperationAction(ISD::UADDO, VT, Custom);
1713     setOperationAction(ISD::SSUBO, VT, Custom);
1714     setOperationAction(ISD::USUBO, VT, Custom);
1715     setOperationAction(ISD::SMULO, VT, Custom);
1716     setOperationAction(ISD::UMULO, VT, Custom);
1717   }
1718
1719   if (!Subtarget->is64Bit()) {
1720     // These libcalls are not available in 32-bit.
1721     setLibcallName(RTLIB::SHL_I128, nullptr);
1722     setLibcallName(RTLIB::SRL_I128, nullptr);
1723     setLibcallName(RTLIB::SRA_I128, nullptr);
1724   }
1725
1726   // Combine sin / cos into one node or libcall if possible.
1727   if (Subtarget->hasSinCos()) {
1728     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1729     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1730     if (Subtarget->isTargetDarwin()) {
1731       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1732       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1733       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1734       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1735     }
1736   }
1737
1738   if (Subtarget->isTargetWin64()) {
1739     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1740     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1741     setOperationAction(ISD::SREM, MVT::i128, Custom);
1742     setOperationAction(ISD::UREM, MVT::i128, Custom);
1743     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1744     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1745   }
1746
1747   // We have target-specific dag combine patterns for the following nodes:
1748   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1749   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1750   setTargetDAGCombine(ISD::BITCAST);
1751   setTargetDAGCombine(ISD::VSELECT);
1752   setTargetDAGCombine(ISD::SELECT);
1753   setTargetDAGCombine(ISD::SHL);
1754   setTargetDAGCombine(ISD::SRA);
1755   setTargetDAGCombine(ISD::SRL);
1756   setTargetDAGCombine(ISD::OR);
1757   setTargetDAGCombine(ISD::AND);
1758   setTargetDAGCombine(ISD::ADD);
1759   setTargetDAGCombine(ISD::FADD);
1760   setTargetDAGCombine(ISD::FSUB);
1761   setTargetDAGCombine(ISD::FMA);
1762   setTargetDAGCombine(ISD::SUB);
1763   setTargetDAGCombine(ISD::LOAD);
1764   setTargetDAGCombine(ISD::MLOAD);
1765   setTargetDAGCombine(ISD::STORE);
1766   setTargetDAGCombine(ISD::MSTORE);
1767   setTargetDAGCombine(ISD::ZERO_EXTEND);
1768   setTargetDAGCombine(ISD::ANY_EXTEND);
1769   setTargetDAGCombine(ISD::SIGN_EXTEND);
1770   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1771   setTargetDAGCombine(ISD::SINT_TO_FP);
1772   setTargetDAGCombine(ISD::UINT_TO_FP);
1773   setTargetDAGCombine(ISD::SETCC);
1774   setTargetDAGCombine(ISD::BUILD_VECTOR);
1775   setTargetDAGCombine(ISD::MUL);
1776   setTargetDAGCombine(ISD::XOR);
1777
1778   computeRegisterProperties(Subtarget->getRegisterInfo());
1779
1780   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1781   MaxStoresPerMemsetOptSize = 8;
1782   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1783   MaxStoresPerMemcpyOptSize = 4;
1784   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1785   MaxStoresPerMemmoveOptSize = 4;
1786   setPrefLoopAlignment(4); // 2^4 bytes.
1787
1788   // A predictable cmov does not hurt on an in-order CPU.
1789   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1790   PredictableSelectIsExpensive = !Subtarget->isAtom();
1791   EnableExtLdPromotion = true;
1792   setPrefFunctionAlignment(4); // 2^4 bytes.
1793
1794   verifyIntrinsicTables();
1795 }
1796
1797 // This has so far only been implemented for 64-bit MachO.
1798 bool X86TargetLowering::useLoadStackGuardNode() const {
1799   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1800 }
1801
1802 TargetLoweringBase::LegalizeTypeAction
1803 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1804   if (ExperimentalVectorWideningLegalization &&
1805       VT.getVectorNumElements() != 1 &&
1806       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1807     return TypeWidenVector;
1808
1809   return TargetLoweringBase::getPreferredVectorAction(VT);
1810 }
1811
1812 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1813                                           EVT VT) const {
1814   if (!VT.isVector())
1815     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1816
1817   const unsigned NumElts = VT.getVectorNumElements();
1818   const EVT EltVT = VT.getVectorElementType();
1819   if (VT.is512BitVector()) {
1820     if (Subtarget->hasAVX512())
1821       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1822           EltVT == MVT::f32 || EltVT == MVT::f64)
1823         switch(NumElts) {
1824         case  8: return MVT::v8i1;
1825         case 16: return MVT::v16i1;
1826       }
1827     if (Subtarget->hasBWI())
1828       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1829         switch(NumElts) {
1830         case 32: return MVT::v32i1;
1831         case 64: return MVT::v64i1;
1832       }
1833   }
1834
1835   if (VT.is256BitVector() || VT.is128BitVector()) {
1836     if (Subtarget->hasVLX())
1837       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1838           EltVT == MVT::f32 || EltVT == MVT::f64)
1839         switch(NumElts) {
1840         case 2: return MVT::v2i1;
1841         case 4: return MVT::v4i1;
1842         case 8: return MVT::v8i1;
1843       }
1844     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1845       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1846         switch(NumElts) {
1847         case  8: return MVT::v8i1;
1848         case 16: return MVT::v16i1;
1849         case 32: return MVT::v32i1;
1850       }
1851   }
1852
1853   return VT.changeVectorElementTypeToInteger();
1854 }
1855
1856 /// Helper for getByValTypeAlignment to determine
1857 /// the desired ByVal argument alignment.
1858 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1859   if (MaxAlign == 16)
1860     return;
1861   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1862     if (VTy->getBitWidth() == 128)
1863       MaxAlign = 16;
1864   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1865     unsigned EltAlign = 0;
1866     getMaxByValAlign(ATy->getElementType(), EltAlign);
1867     if (EltAlign > MaxAlign)
1868       MaxAlign = EltAlign;
1869   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1870     for (auto *EltTy : STy->elements()) {
1871       unsigned EltAlign = 0;
1872       getMaxByValAlign(EltTy, EltAlign);
1873       if (EltAlign > MaxAlign)
1874         MaxAlign = EltAlign;
1875       if (MaxAlign == 16)
1876         break;
1877     }
1878   }
1879 }
1880
1881 /// Return the desired alignment for ByVal aggregate
1882 /// function arguments in the caller parameter area. For X86, aggregates
1883 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1884 /// are at 4-byte boundaries.
1885 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1886                                                   const DataLayout &DL) const {
1887   if (Subtarget->is64Bit()) {
1888     // Max of 8 and alignment of type.
1889     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1890     if (TyAlign > 8)
1891       return TyAlign;
1892     return 8;
1893   }
1894
1895   unsigned Align = 4;
1896   if (Subtarget->hasSSE1())
1897     getMaxByValAlign(Ty, Align);
1898   return Align;
1899 }
1900
1901 /// Returns the target specific optimal type for load
1902 /// and store operations as a result of memset, memcpy, and memmove
1903 /// lowering. If DstAlign is zero that means it's safe to destination
1904 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1905 /// means there isn't a need to check it against alignment requirement,
1906 /// probably because the source does not need to be loaded. If 'IsMemset' is
1907 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1908 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1909 /// source is constant so it does not need to be loaded.
1910 /// It returns EVT::Other if the type should be determined using generic
1911 /// target-independent logic.
1912 EVT
1913 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1914                                        unsigned DstAlign, unsigned SrcAlign,
1915                                        bool IsMemset, bool ZeroMemset,
1916                                        bool MemcpyStrSrc,
1917                                        MachineFunction &MF) const {
1918   const Function *F = MF.getFunction();
1919   if ((!IsMemset || ZeroMemset) &&
1920       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1921     if (Size >= 16 &&
1922         (!Subtarget->isUnalignedMem16Slow() ||
1923          ((DstAlign == 0 || DstAlign >= 16) &&
1924           (SrcAlign == 0 || SrcAlign >= 16)))) {
1925       if (Size >= 32) {
1926         // FIXME: Check if unaligned 32-byte accesses are slow.
1927         if (Subtarget->hasInt256())
1928           return MVT::v8i32;
1929         if (Subtarget->hasFp256())
1930           return MVT::v8f32;
1931       }
1932       if (Subtarget->hasSSE2())
1933         return MVT::v4i32;
1934       if (Subtarget->hasSSE1())
1935         return MVT::v4f32;
1936     } else if (!MemcpyStrSrc && Size >= 8 &&
1937                !Subtarget->is64Bit() &&
1938                Subtarget->hasSSE2()) {
1939       // Do not use f64 to lower memcpy if source is string constant. It's
1940       // better to use i32 to avoid the loads.
1941       return MVT::f64;
1942     }
1943   }
1944   // This is a compromise. If we reach here, unaligned accesses may be slow on
1945   // this target. However, creating smaller, aligned accesses could be even
1946   // slower and would certainly be a lot more code.
1947   if (Subtarget->is64Bit() && Size >= 8)
1948     return MVT::i64;
1949   return MVT::i32;
1950 }
1951
1952 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1953   if (VT == MVT::f32)
1954     return X86ScalarSSEf32;
1955   else if (VT == MVT::f64)
1956     return X86ScalarSSEf64;
1957   return true;
1958 }
1959
1960 bool
1961 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1962                                                   unsigned,
1963                                                   unsigned,
1964                                                   bool *Fast) const {
1965   if (Fast) {
1966     switch (VT.getSizeInBits()) {
1967     default:
1968       // 8-byte and under are always assumed to be fast.
1969       *Fast = true;
1970       break;
1971     case 128:
1972       *Fast = !Subtarget->isUnalignedMem16Slow();
1973       break;
1974     case 256:
1975       *Fast = !Subtarget->isUnalignedMem32Slow();
1976       break;
1977     // TODO: What about AVX-512 (512-bit) accesses?
1978     }
1979   }
1980   // Misaligned accesses of any size are always allowed.
1981   return true;
1982 }
1983
1984 /// Return the entry encoding for a jump table in the
1985 /// current function.  The returned value is a member of the
1986 /// MachineJumpTableInfo::JTEntryKind enum.
1987 unsigned X86TargetLowering::getJumpTableEncoding() const {
1988   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1989   // symbol.
1990   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1991       Subtarget->isPICStyleGOT())
1992     return MachineJumpTableInfo::EK_Custom32;
1993
1994   // Otherwise, use the normal jump table encoding heuristics.
1995   return TargetLowering::getJumpTableEncoding();
1996 }
1997
1998 bool X86TargetLowering::useSoftFloat() const {
1999   return Subtarget->useSoftFloat();
2000 }
2001
2002 const MCExpr *
2003 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2004                                              const MachineBasicBlock *MBB,
2005                                              unsigned uid,MCContext &Ctx) const{
2006   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2007          Subtarget->isPICStyleGOT());
2008   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2009   // entries.
2010   return MCSymbolRefExpr::create(MBB->getSymbol(),
2011                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2012 }
2013
2014 /// Returns relocation base for the given PIC jumptable.
2015 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2016                                                     SelectionDAG &DAG) const {
2017   if (!Subtarget->is64Bit())
2018     // This doesn't have SDLoc associated with it, but is not really the
2019     // same as a Register.
2020     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2021                        getPointerTy(DAG.getDataLayout()));
2022   return Table;
2023 }
2024
2025 /// This returns the relocation base for the given PIC jumptable,
2026 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2027 const MCExpr *X86TargetLowering::
2028 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2029                              MCContext &Ctx) const {
2030   // X86-64 uses RIP relative addressing based on the jump table label.
2031   if (Subtarget->isPICStyleRIPRel())
2032     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2033
2034   // Otherwise, the reference is relative to the PIC base.
2035   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2036 }
2037
2038 std::pair<const TargetRegisterClass *, uint8_t>
2039 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2040                                            MVT VT) const {
2041   const TargetRegisterClass *RRC = nullptr;
2042   uint8_t Cost = 1;
2043   switch (VT.SimpleTy) {
2044   default:
2045     return TargetLowering::findRepresentativeClass(TRI, VT);
2046   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2047     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2048     break;
2049   case MVT::x86mmx:
2050     RRC = &X86::VR64RegClass;
2051     break;
2052   case MVT::f32: case MVT::f64:
2053   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2054   case MVT::v4f32: case MVT::v2f64:
2055   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2056   case MVT::v4f64:
2057     RRC = &X86::VR128RegClass;
2058     break;
2059   }
2060   return std::make_pair(RRC, Cost);
2061 }
2062
2063 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2064                                                unsigned &Offset) const {
2065   if (!Subtarget->isTargetLinux())
2066     return false;
2067
2068   if (Subtarget->is64Bit()) {
2069     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2070     Offset = 0x28;
2071     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2072       AddressSpace = 256;
2073     else
2074       AddressSpace = 257;
2075   } else {
2076     // %gs:0x14 on i386
2077     Offset = 0x14;
2078     AddressSpace = 256;
2079   }
2080   return true;
2081 }
2082
2083 /// Android provides a fixed TLS slot for the SafeStack pointer.
2084 /// See the definition of TLS_SLOT_SAFESTACK in
2085 /// https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2086 bool X86TargetLowering::getSafeStackPointerLocation(unsigned &AddressSpace,
2087                                                     unsigned &Offset) const {
2088   if (!Subtarget->isTargetAndroid())
2089     return false;
2090
2091   if (Subtarget->is64Bit()) {
2092     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2093     Offset = 0x48;
2094     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2095       AddressSpace = 256;
2096     else
2097       AddressSpace = 257;
2098   } else {
2099     // %gs:0x24 on i386
2100     Offset = 0x24;
2101     AddressSpace = 256;
2102   }
2103   return true;
2104 }
2105
2106 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2107                                             unsigned DestAS) const {
2108   assert(SrcAS != DestAS && "Expected different address spaces!");
2109
2110   return SrcAS < 256 && DestAS < 256;
2111 }
2112
2113 //===----------------------------------------------------------------------===//
2114 //               Return Value Calling Convention Implementation
2115 //===----------------------------------------------------------------------===//
2116
2117 #include "X86GenCallingConv.inc"
2118
2119 bool X86TargetLowering::CanLowerReturn(
2120     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2121     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2122   SmallVector<CCValAssign, 16> RVLocs;
2123   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2124   return CCInfo.CheckReturn(Outs, RetCC_X86);
2125 }
2126
2127 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2128   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2129   return ScratchRegs;
2130 }
2131
2132 SDValue
2133 X86TargetLowering::LowerReturn(SDValue Chain,
2134                                CallingConv::ID CallConv, bool isVarArg,
2135                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2136                                const SmallVectorImpl<SDValue> &OutVals,
2137                                SDLoc dl, SelectionDAG &DAG) const {
2138   MachineFunction &MF = DAG.getMachineFunction();
2139   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2140
2141   SmallVector<CCValAssign, 16> RVLocs;
2142   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2143   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2144
2145   SDValue Flag;
2146   SmallVector<SDValue, 6> RetOps;
2147   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2148   // Operand #1 = Bytes To Pop
2149   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2150                    MVT::i16));
2151
2152   // Copy the result values into the output registers.
2153   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2154     CCValAssign &VA = RVLocs[i];
2155     assert(VA.isRegLoc() && "Can only return in registers!");
2156     SDValue ValToCopy = OutVals[i];
2157     EVT ValVT = ValToCopy.getValueType();
2158
2159     // Promote values to the appropriate types.
2160     if (VA.getLocInfo() == CCValAssign::SExt)
2161       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2162     else if (VA.getLocInfo() == CCValAssign::ZExt)
2163       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2164     else if (VA.getLocInfo() == CCValAssign::AExt) {
2165       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2166         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2167       else
2168         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2169     }
2170     else if (VA.getLocInfo() == CCValAssign::BCvt)
2171       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2172
2173     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2174            "Unexpected FP-extend for return value.");
2175
2176     // If this is x86-64, and we disabled SSE, we can't return FP values,
2177     // or SSE or MMX vectors.
2178     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2179          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2180           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2181       report_fatal_error("SSE register return with SSE disabled");
2182     }
2183     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2184     // llvm-gcc has never done it right and no one has noticed, so this
2185     // should be OK for now.
2186     if (ValVT == MVT::f64 &&
2187         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2188       report_fatal_error("SSE2 register return with SSE2 disabled");
2189
2190     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2191     // the RET instruction and handled by the FP Stackifier.
2192     if (VA.getLocReg() == X86::FP0 ||
2193         VA.getLocReg() == X86::FP1) {
2194       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2195       // change the value to the FP stack register class.
2196       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2197         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2198       RetOps.push_back(ValToCopy);
2199       // Don't emit a copytoreg.
2200       continue;
2201     }
2202
2203     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2204     // which is returned in RAX / RDX.
2205     if (Subtarget->is64Bit()) {
2206       if (ValVT == MVT::x86mmx) {
2207         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2208           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2209           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2210                                   ValToCopy);
2211           // If we don't have SSE2 available, convert to v4f32 so the generated
2212           // register is legal.
2213           if (!Subtarget->hasSSE2())
2214             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2215         }
2216       }
2217     }
2218
2219     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2220     Flag = Chain.getValue(1);
2221     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2222   }
2223
2224   // All x86 ABIs require that for returning structs by value we copy
2225   // the sret argument into %rax/%eax (depending on ABI) for the return.
2226   // We saved the argument into a virtual register in the entry block,
2227   // so now we copy the value out and into %rax/%eax.
2228   //
2229   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2230   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2231   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2232   // either case FuncInfo->setSRetReturnReg() will have been called.
2233   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2234     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2235                                      getPointerTy(MF.getDataLayout()));
2236
2237     unsigned RetValReg
2238         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2239           X86::RAX : X86::EAX;
2240     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2241     Flag = Chain.getValue(1);
2242
2243     // RAX/EAX now acts like a return value.
2244     RetOps.push_back(
2245         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2246   }
2247
2248   RetOps[0] = Chain;  // Update chain.
2249
2250   // Add the flag if we have it.
2251   if (Flag.getNode())
2252     RetOps.push_back(Flag);
2253
2254   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2255 }
2256
2257 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2258   if (N->getNumValues() != 1)
2259     return false;
2260   if (!N->hasNUsesOfValue(1, 0))
2261     return false;
2262
2263   SDValue TCChain = Chain;
2264   SDNode *Copy = *N->use_begin();
2265   if (Copy->getOpcode() == ISD::CopyToReg) {
2266     // If the copy has a glue operand, we conservatively assume it isn't safe to
2267     // perform a tail call.
2268     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2269       return false;
2270     TCChain = Copy->getOperand(0);
2271   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2272     return false;
2273
2274   bool HasRet = false;
2275   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2276        UI != UE; ++UI) {
2277     if (UI->getOpcode() != X86ISD::RET_FLAG)
2278       return false;
2279     // If we are returning more than one value, we can definitely
2280     // not make a tail call see PR19530
2281     if (UI->getNumOperands() > 4)
2282       return false;
2283     if (UI->getNumOperands() == 4 &&
2284         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2285       return false;
2286     HasRet = true;
2287   }
2288
2289   if (!HasRet)
2290     return false;
2291
2292   Chain = TCChain;
2293   return true;
2294 }
2295
2296 EVT
2297 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2298                                             ISD::NodeType ExtendKind) const {
2299   MVT ReturnMVT;
2300   // TODO: Is this also valid on 32-bit?
2301   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2302     ReturnMVT = MVT::i8;
2303   else
2304     ReturnMVT = MVT::i32;
2305
2306   EVT MinVT = getRegisterType(Context, ReturnMVT);
2307   return VT.bitsLT(MinVT) ? MinVT : VT;
2308 }
2309
2310 /// Lower the result values of a call into the
2311 /// appropriate copies out of appropriate physical registers.
2312 ///
2313 SDValue
2314 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2315                                    CallingConv::ID CallConv, bool isVarArg,
2316                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2317                                    SDLoc dl, SelectionDAG &DAG,
2318                                    SmallVectorImpl<SDValue> &InVals) const {
2319
2320   // Assign locations to each value returned by this call.
2321   SmallVector<CCValAssign, 16> RVLocs;
2322   bool Is64Bit = Subtarget->is64Bit();
2323   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2324                  *DAG.getContext());
2325   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2326
2327   // Copy all of the result registers out of their specified physreg.
2328   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2329     CCValAssign &VA = RVLocs[i];
2330     EVT CopyVT = VA.getLocVT();
2331
2332     // If this is x86-64, and we disabled SSE, we can't return FP values
2333     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2334         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2335       report_fatal_error("SSE register return with SSE disabled");
2336     }
2337
2338     // If we prefer to use the value in xmm registers, copy it out as f80 and
2339     // use a truncate to move it from fp stack reg to xmm reg.
2340     bool RoundAfterCopy = false;
2341     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2342         isScalarFPTypeInSSEReg(VA.getValVT())) {
2343       CopyVT = MVT::f80;
2344       RoundAfterCopy = (CopyVT != VA.getLocVT());
2345     }
2346
2347     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2348                                CopyVT, InFlag).getValue(1);
2349     SDValue Val = Chain.getValue(0);
2350
2351     if (RoundAfterCopy)
2352       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2353                         // This truncation won't change the value.
2354                         DAG.getIntPtrConstant(1, dl));
2355
2356     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2357       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2358
2359     InFlag = Chain.getValue(2);
2360     InVals.push_back(Val);
2361   }
2362
2363   return Chain;
2364 }
2365
2366 //===----------------------------------------------------------------------===//
2367 //                C & StdCall & Fast Calling Convention implementation
2368 //===----------------------------------------------------------------------===//
2369 //  StdCall calling convention seems to be standard for many Windows' API
2370 //  routines and around. It differs from C calling convention just a little:
2371 //  callee should clean up the stack, not caller. Symbols should be also
2372 //  decorated in some fancy way :) It doesn't support any vector arguments.
2373 //  For info on fast calling convention see Fast Calling Convention (tail call)
2374 //  implementation LowerX86_32FastCCCallTo.
2375
2376 /// CallIsStructReturn - Determines whether a call uses struct return
2377 /// semantics.
2378 enum StructReturnType {
2379   NotStructReturn,
2380   RegStructReturn,
2381   StackStructReturn
2382 };
2383 static StructReturnType
2384 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2385   if (Outs.empty())
2386     return NotStructReturn;
2387
2388   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2389   if (!Flags.isSRet())
2390     return NotStructReturn;
2391   if (Flags.isInReg())
2392     return RegStructReturn;
2393   return StackStructReturn;
2394 }
2395
2396 /// Determines whether a function uses struct return semantics.
2397 static StructReturnType
2398 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2399   if (Ins.empty())
2400     return NotStructReturn;
2401
2402   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2403   if (!Flags.isSRet())
2404     return NotStructReturn;
2405   if (Flags.isInReg())
2406     return RegStructReturn;
2407   return StackStructReturn;
2408 }
2409
2410 /// Make a copy of an aggregate at address specified by "Src" to address
2411 /// "Dst" with size and alignment information specified by the specific
2412 /// parameter attribute. The copy will be passed as a byval function parameter.
2413 static SDValue
2414 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2415                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2416                           SDLoc dl) {
2417   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2418
2419   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2420                        /*isVolatile*/false, /*AlwaysInline=*/true,
2421                        /*isTailCall*/false,
2422                        MachinePointerInfo(), MachinePointerInfo());
2423 }
2424
2425 /// Return true if the calling convention is one that
2426 /// supports tail call optimization.
2427 static bool IsTailCallConvention(CallingConv::ID CC) {
2428   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2429           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2430 }
2431
2432 /// \brief Return true if the calling convention is a C calling convention.
2433 static bool IsCCallConvention(CallingConv::ID CC) {
2434   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2435           CC == CallingConv::X86_64_SysV);
2436 }
2437
2438 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2439   auto Attr =
2440       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2441   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2442     return false;
2443
2444   CallSite CS(CI);
2445   CallingConv::ID CalleeCC = CS.getCallingConv();
2446   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2447     return false;
2448
2449   return true;
2450 }
2451
2452 /// Return true if the function is being made into
2453 /// a tailcall target by changing its ABI.
2454 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2455                                    bool GuaranteedTailCallOpt) {
2456   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2457 }
2458
2459 SDValue
2460 X86TargetLowering::LowerMemArgument(SDValue Chain,
2461                                     CallingConv::ID CallConv,
2462                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2463                                     SDLoc dl, SelectionDAG &DAG,
2464                                     const CCValAssign &VA,
2465                                     MachineFrameInfo *MFI,
2466                                     unsigned i) const {
2467   // Create the nodes corresponding to a load from this parameter slot.
2468   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2469   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2470       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2471   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2472   EVT ValVT;
2473
2474   // If value is passed by pointer we have address passed instead of the value
2475   // itself.
2476   bool ExtendedInMem = VA.isExtInLoc() &&
2477     VA.getValVT().getScalarType() == MVT::i1;
2478
2479   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2480     ValVT = VA.getLocVT();
2481   else
2482     ValVT = VA.getValVT();
2483
2484   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2485   // changed with more analysis.
2486   // In case of tail call optimization mark all arguments mutable. Since they
2487   // could be overwritten by lowering of arguments in case of a tail call.
2488   if (Flags.isByVal()) {
2489     unsigned Bytes = Flags.getByValSize();
2490     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2491     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2492     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2493   } else {
2494     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2495                                     VA.getLocMemOffset(), isImmutable);
2496     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2497     SDValue Val = DAG.getLoad(
2498         ValVT, dl, Chain, FIN,
2499         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2500         false, false, 0);
2501     return ExtendedInMem ?
2502       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2503   }
2504 }
2505
2506 // FIXME: Get this from tablegen.
2507 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2508                                                 const X86Subtarget *Subtarget) {
2509   assert(Subtarget->is64Bit());
2510
2511   if (Subtarget->isCallingConvWin64(CallConv)) {
2512     static const MCPhysReg GPR64ArgRegsWin64[] = {
2513       X86::RCX, X86::RDX, X86::R8,  X86::R9
2514     };
2515     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2516   }
2517
2518   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2519     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2520   };
2521   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2522 }
2523
2524 // FIXME: Get this from tablegen.
2525 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2526                                                 CallingConv::ID CallConv,
2527                                                 const X86Subtarget *Subtarget) {
2528   assert(Subtarget->is64Bit());
2529   if (Subtarget->isCallingConvWin64(CallConv)) {
2530     // The XMM registers which might contain var arg parameters are shadowed
2531     // in their paired GPR.  So we only need to save the GPR to their home
2532     // slots.
2533     // TODO: __vectorcall will change this.
2534     return None;
2535   }
2536
2537   const Function *Fn = MF.getFunction();
2538   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2539   bool isSoftFloat = Subtarget->useSoftFloat();
2540   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2541          "SSE register cannot be used when SSE is disabled!");
2542   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2543     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2544     // registers.
2545     return None;
2546
2547   static const MCPhysReg XMMArgRegs64Bit[] = {
2548     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2549     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2550   };
2551   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2552 }
2553
2554 SDValue X86TargetLowering::LowerFormalArguments(
2555     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2556     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2557     SmallVectorImpl<SDValue> &InVals) const {
2558   MachineFunction &MF = DAG.getMachineFunction();
2559   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2560   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2561
2562   const Function* Fn = MF.getFunction();
2563   if (Fn->hasExternalLinkage() &&
2564       Subtarget->isTargetCygMing() &&
2565       Fn->getName() == "main")
2566     FuncInfo->setForceFramePointer(true);
2567
2568   MachineFrameInfo *MFI = MF.getFrameInfo();
2569   bool Is64Bit = Subtarget->is64Bit();
2570   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2571
2572   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2573          "Var args not supported with calling convention fastcc, ghc or hipe");
2574
2575   // Assign locations to all of the incoming arguments.
2576   SmallVector<CCValAssign, 16> ArgLocs;
2577   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2578
2579   // Allocate shadow area for Win64
2580   if (IsWin64)
2581     CCInfo.AllocateStack(32, 8);
2582
2583   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2584
2585   unsigned LastVal = ~0U;
2586   SDValue ArgValue;
2587   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2588     CCValAssign &VA = ArgLocs[i];
2589     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2590     // places.
2591     assert(VA.getValNo() != LastVal &&
2592            "Don't support value assigned to multiple locs yet");
2593     (void)LastVal;
2594     LastVal = VA.getValNo();
2595
2596     if (VA.isRegLoc()) {
2597       EVT RegVT = VA.getLocVT();
2598       const TargetRegisterClass *RC;
2599       if (RegVT == MVT::i32)
2600         RC = &X86::GR32RegClass;
2601       else if (Is64Bit && RegVT == MVT::i64)
2602         RC = &X86::GR64RegClass;
2603       else if (RegVT == MVT::f32)
2604         RC = &X86::FR32RegClass;
2605       else if (RegVT == MVT::f64)
2606         RC = &X86::FR64RegClass;
2607       else if (RegVT.is512BitVector())
2608         RC = &X86::VR512RegClass;
2609       else if (RegVT.is256BitVector())
2610         RC = &X86::VR256RegClass;
2611       else if (RegVT.is128BitVector())
2612         RC = &X86::VR128RegClass;
2613       else if (RegVT == MVT::x86mmx)
2614         RC = &X86::VR64RegClass;
2615       else if (RegVT == MVT::i1)
2616         RC = &X86::VK1RegClass;
2617       else if (RegVT == MVT::v8i1)
2618         RC = &X86::VK8RegClass;
2619       else if (RegVT == MVT::v16i1)
2620         RC = &X86::VK16RegClass;
2621       else if (RegVT == MVT::v32i1)
2622         RC = &X86::VK32RegClass;
2623       else if (RegVT == MVT::v64i1)
2624         RC = &X86::VK64RegClass;
2625       else
2626         llvm_unreachable("Unknown argument type!");
2627
2628       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2629       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2630
2631       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2632       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2633       // right size.
2634       if (VA.getLocInfo() == CCValAssign::SExt)
2635         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2636                                DAG.getValueType(VA.getValVT()));
2637       else if (VA.getLocInfo() == CCValAssign::ZExt)
2638         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2639                                DAG.getValueType(VA.getValVT()));
2640       else if (VA.getLocInfo() == CCValAssign::BCvt)
2641         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2642
2643       if (VA.isExtInLoc()) {
2644         // Handle MMX values passed in XMM regs.
2645         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2646           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2647         else
2648           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2649       }
2650     } else {
2651       assert(VA.isMemLoc());
2652       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2653     }
2654
2655     // If value is passed via pointer - do a load.
2656     if (VA.getLocInfo() == CCValAssign::Indirect)
2657       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2658                              MachinePointerInfo(), false, false, false, 0);
2659
2660     InVals.push_back(ArgValue);
2661   }
2662
2663   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2664     // All x86 ABIs require that for returning structs by value we copy the
2665     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2666     // the argument into a virtual register so that we can access it from the
2667     // return points.
2668     if (Ins[i].Flags.isSRet()) {
2669       unsigned Reg = FuncInfo->getSRetReturnReg();
2670       if (!Reg) {
2671         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2672         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2673         FuncInfo->setSRetReturnReg(Reg);
2674       }
2675       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2676       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2677       break;
2678     }
2679   }
2680
2681   unsigned StackSize = CCInfo.getNextStackOffset();
2682   // Align stack specially for tail calls.
2683   if (FuncIsMadeTailCallSafe(CallConv,
2684                              MF.getTarget().Options.GuaranteedTailCallOpt))
2685     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2686
2687   // If the function takes variable number of arguments, make a frame index for
2688   // the start of the first vararg value... for expansion of llvm.va_start. We
2689   // can skip this if there are no va_start calls.
2690   if (MFI->hasVAStart() &&
2691       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2692                    CallConv != CallingConv::X86_ThisCall))) {
2693     FuncInfo->setVarArgsFrameIndex(
2694         MFI->CreateFixedObject(1, StackSize, true));
2695   }
2696
2697   MachineModuleInfo &MMI = MF.getMMI();
2698   const Function *WinEHParent = nullptr;
2699   if (MMI.hasWinEHFuncInfo(Fn))
2700     WinEHParent = MMI.getWinEHParent(Fn);
2701   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2702
2703   // Figure out if XMM registers are in use.
2704   assert(!(Subtarget->useSoftFloat() &&
2705            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2706          "SSE register cannot be used when SSE is disabled!");
2707
2708   // 64-bit calling conventions support varargs and register parameters, so we
2709   // have to do extra work to spill them in the prologue.
2710   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2711     // Find the first unallocated argument registers.
2712     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2713     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2714     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2715     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2716     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2717            "SSE register cannot be used when SSE is disabled!");
2718
2719     // Gather all the live in physical registers.
2720     SmallVector<SDValue, 6> LiveGPRs;
2721     SmallVector<SDValue, 8> LiveXMMRegs;
2722     SDValue ALVal;
2723     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2724       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2725       LiveGPRs.push_back(
2726           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2727     }
2728     if (!ArgXMMs.empty()) {
2729       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2730       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2731       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2732         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2733         LiveXMMRegs.push_back(
2734             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2735       }
2736     }
2737
2738     if (IsWin64) {
2739       // Get to the caller-allocated home save location.  Add 8 to account
2740       // for the return address.
2741       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2742       FuncInfo->setRegSaveFrameIndex(
2743           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2744       // Fixup to set vararg frame on shadow area (4 x i64).
2745       if (NumIntRegs < 4)
2746         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2747     } else {
2748       // For X86-64, if there are vararg parameters that are passed via
2749       // registers, then we must store them to their spots on the stack so
2750       // they may be loaded by deferencing the result of va_next.
2751       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2752       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2753       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2754           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2755     }
2756
2757     // Store the integer parameter registers.
2758     SmallVector<SDValue, 8> MemOps;
2759     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2760                                       getPointerTy(DAG.getDataLayout()));
2761     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2762     for (SDValue Val : LiveGPRs) {
2763       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2764                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2765       SDValue Store =
2766           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2767                        MachinePointerInfo::getFixedStack(
2768                            DAG.getMachineFunction(),
2769                            FuncInfo->getRegSaveFrameIndex(), Offset),
2770                        false, false, 0);
2771       MemOps.push_back(Store);
2772       Offset += 8;
2773     }
2774
2775     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2776       // Now store the XMM (fp + vector) parameter registers.
2777       SmallVector<SDValue, 12> SaveXMMOps;
2778       SaveXMMOps.push_back(Chain);
2779       SaveXMMOps.push_back(ALVal);
2780       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2781                              FuncInfo->getRegSaveFrameIndex(), dl));
2782       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2783                              FuncInfo->getVarArgsFPOffset(), dl));
2784       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2785                         LiveXMMRegs.end());
2786       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2787                                    MVT::Other, SaveXMMOps));
2788     }
2789
2790     if (!MemOps.empty())
2791       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2792   }
2793
2794   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2795     // Find the largest legal vector type.
2796     MVT VecVT = MVT::Other;
2797     // FIXME: Only some x86_32 calling conventions support AVX512.
2798     if (Subtarget->hasAVX512() &&
2799         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2800                      CallConv == CallingConv::Intel_OCL_BI)))
2801       VecVT = MVT::v16f32;
2802     else if (Subtarget->hasAVX())
2803       VecVT = MVT::v8f32;
2804     else if (Subtarget->hasSSE2())
2805       VecVT = MVT::v4f32;
2806
2807     // We forward some GPRs and some vector types.
2808     SmallVector<MVT, 2> RegParmTypes;
2809     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2810     RegParmTypes.push_back(IntVT);
2811     if (VecVT != MVT::Other)
2812       RegParmTypes.push_back(VecVT);
2813
2814     // Compute the set of forwarded registers. The rest are scratch.
2815     SmallVectorImpl<ForwardedRegister> &Forwards =
2816         FuncInfo->getForwardedMustTailRegParms();
2817     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2818
2819     // Conservatively forward AL on x86_64, since it might be used for varargs.
2820     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2821       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2822       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2823     }
2824
2825     // Copy all forwards from physical to virtual registers.
2826     for (ForwardedRegister &F : Forwards) {
2827       // FIXME: Can we use a less constrained schedule?
2828       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2829       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2830       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2831     }
2832   }
2833
2834   // Some CCs need callee pop.
2835   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2836                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2837     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2838   } else {
2839     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2840     // If this is an sret function, the return should pop the hidden pointer.
2841     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2842         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2843         argsAreStructReturn(Ins) == StackStructReturn)
2844       FuncInfo->setBytesToPopOnReturn(4);
2845   }
2846
2847   if (!Is64Bit) {
2848     // RegSaveFrameIndex is X86-64 only.
2849     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2850     if (CallConv == CallingConv::X86_FastCall ||
2851         CallConv == CallingConv::X86_ThisCall)
2852       // fastcc functions can't have varargs.
2853       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2854   }
2855
2856   FuncInfo->setArgumentStackSize(StackSize);
2857
2858   if (IsWinEHParent) {
2859     if (Is64Bit) {
2860       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2861       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2862       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2863       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2864       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2865                            MachinePointerInfo::getFixedStack(
2866                                DAG.getMachineFunction(), UnwindHelpFI),
2867                            /*isVolatile=*/true,
2868                            /*isNonTemporal=*/false, /*Alignment=*/0);
2869     } else {
2870       // Functions using Win32 EH are considered to have opaque SP adjustments
2871       // to force local variables to be addressed from the frame or base
2872       // pointers.
2873       MFI->setHasOpaqueSPAdjustment(true);
2874     }
2875   }
2876
2877   return Chain;
2878 }
2879
2880 SDValue
2881 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2882                                     SDValue StackPtr, SDValue Arg,
2883                                     SDLoc dl, SelectionDAG &DAG,
2884                                     const CCValAssign &VA,
2885                                     ISD::ArgFlagsTy Flags) const {
2886   unsigned LocMemOffset = VA.getLocMemOffset();
2887   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2888   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2889                        StackPtr, PtrOff);
2890   if (Flags.isByVal())
2891     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2892
2893   return DAG.getStore(
2894       Chain, dl, Arg, PtrOff,
2895       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2896       false, false, 0);
2897 }
2898
2899 /// Emit a load of return address if tail call
2900 /// optimization is performed and it is required.
2901 SDValue
2902 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2903                                            SDValue &OutRetAddr, SDValue Chain,
2904                                            bool IsTailCall, bool Is64Bit,
2905                                            int FPDiff, SDLoc dl) const {
2906   // Adjust the Return address stack slot.
2907   EVT VT = getPointerTy(DAG.getDataLayout());
2908   OutRetAddr = getReturnAddressFrameIndex(DAG);
2909
2910   // Load the "old" Return address.
2911   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2912                            false, false, false, 0);
2913   return SDValue(OutRetAddr.getNode(), 1);
2914 }
2915
2916 /// Emit a store of the return address if tail call
2917 /// optimization is performed and it is required (FPDiff!=0).
2918 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2919                                         SDValue Chain, SDValue RetAddrFrIdx,
2920                                         EVT PtrVT, unsigned SlotSize,
2921                                         int FPDiff, SDLoc dl) {
2922   // Store the return address to the appropriate stack slot.
2923   if (!FPDiff) return Chain;
2924   // Calculate the new stack slot for the return address.
2925   int NewReturnAddrFI =
2926     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2927                                          false);
2928   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2929   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2930                        MachinePointerInfo::getFixedStack(
2931                            DAG.getMachineFunction(), NewReturnAddrFI),
2932                        false, false, 0);
2933   return Chain;
2934 }
2935
2936 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2937 /// operation of specified width.
2938 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2939                        SDValue V2) {
2940   unsigned NumElems = VT.getVectorNumElements();
2941   SmallVector<int, 8> Mask;
2942   Mask.push_back(NumElems);
2943   for (unsigned i = 1; i != NumElems; ++i)
2944     Mask.push_back(i);
2945   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2946 }
2947
2948 /// Check if the fall through instruction after a call site is unreachable.
2949 /// FIXME: This will fail if there are interesting non-code generating IR
2950 /// instructions between the call and the unreachable (lifetime.end). In
2951 /// practice, this should be rare because optimizations like to delete non-call
2952 /// code before unreachable.
2953 static bool isCallFollowedByUnreachable(ImmutableCallSite CS) {
2954   const Instruction *NextInst;
2955   if (auto *II = dyn_cast<InvokeInst>(CS.getInstruction()))
2956     NextInst = II->getNormalDest()->getFirstNonPHIOrDbg();
2957   else
2958     NextInst = CS.getInstruction()->getNextNode();
2959   return isa<UnreachableInst>(NextInst);
2960 }
2961
2962 SDValue
2963 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2964                              SmallVectorImpl<SDValue> &InVals) const {
2965   SelectionDAG &DAG                     = CLI.DAG;
2966   SDLoc &dl                             = CLI.DL;
2967   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2968   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2969   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2970   SDValue Chain                         = CLI.Chain;
2971   SDValue Callee                        = CLI.Callee;
2972   CallingConv::ID CallConv              = CLI.CallConv;
2973   bool &isTailCall                      = CLI.IsTailCall;
2974   bool isVarArg                         = CLI.IsVarArg;
2975
2976   MachineFunction &MF = DAG.getMachineFunction();
2977   bool Is64Bit        = Subtarget->is64Bit();
2978   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2979   StructReturnType SR = callIsStructReturn(Outs);
2980   bool IsSibcall      = false;
2981   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2982   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2983
2984   if (Attr.getValueAsString() == "true")
2985     isTailCall = false;
2986
2987   if (Subtarget->isPICStyleGOT() &&
2988       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2989     // If we are using a GOT, disable tail calls to external symbols with
2990     // default visibility. Tail calling such a symbol requires using a GOT
2991     // relocation, which forces early binding of the symbol. This breaks code
2992     // that require lazy function symbol resolution. Using musttail or
2993     // GuaranteedTailCallOpt will override this.
2994     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2995     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2996                G->getGlobal()->hasDefaultVisibility()))
2997       isTailCall = false;
2998   }
2999
3000   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3001   if (IsMustTail) {
3002     // Force this to be a tail call.  The verifier rules are enough to ensure
3003     // that we can lower this successfully without moving the return address
3004     // around.
3005     isTailCall = true;
3006   } else if (isTailCall) {
3007     // Check if it's really possible to do a tail call.
3008     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3009                     isVarArg, SR != NotStructReturn,
3010                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3011                     Outs, OutVals, Ins, DAG);
3012
3013     // Sibcalls are automatically detected tailcalls which do not require
3014     // ABI changes.
3015     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3016       IsSibcall = true;
3017
3018     if (isTailCall)
3019       ++NumTailCalls;
3020   }
3021
3022   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
3023          "Var args not supported with calling convention fastcc, ghc or hipe");
3024
3025   // Analyze operands of the call, assigning locations to each operand.
3026   SmallVector<CCValAssign, 16> ArgLocs;
3027   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3028
3029   // Allocate shadow area for Win64
3030   if (IsWin64)
3031     CCInfo.AllocateStack(32, 8);
3032
3033   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3034
3035   // Get a count of how many bytes are to be pushed on the stack.
3036   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3037   if (IsSibcall)
3038     // This is a sibcall. The memory operands are available in caller's
3039     // own caller's stack.
3040     NumBytes = 0;
3041   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3042            IsTailCallConvention(CallConv))
3043     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3044
3045   int FPDiff = 0;
3046   if (isTailCall && !IsSibcall && !IsMustTail) {
3047     // Lower arguments at fp - stackoffset + fpdiff.
3048     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3049
3050     FPDiff = NumBytesCallerPushed - NumBytes;
3051
3052     // Set the delta of movement of the returnaddr stackslot.
3053     // But only set if delta is greater than previous delta.
3054     if (FPDiff < X86Info->getTCReturnAddrDelta())
3055       X86Info->setTCReturnAddrDelta(FPDiff);
3056   }
3057
3058   unsigned NumBytesToPush = NumBytes;
3059   unsigned NumBytesToPop = NumBytes;
3060
3061   // If we have an inalloca argument, all stack space has already been allocated
3062   // for us and be right at the top of the stack.  We don't support multiple
3063   // arguments passed in memory when using inalloca.
3064   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3065     NumBytesToPush = 0;
3066     if (!ArgLocs.back().isMemLoc())
3067       report_fatal_error("cannot use inalloca attribute on a register "
3068                          "parameter");
3069     if (ArgLocs.back().getLocMemOffset() != 0)
3070       report_fatal_error("any parameter with the inalloca attribute must be "
3071                          "the only memory argument");
3072   }
3073
3074   if (!IsSibcall)
3075     Chain = DAG.getCALLSEQ_START(
3076         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3077
3078   SDValue RetAddrFrIdx;
3079   // Load return address for tail calls.
3080   if (isTailCall && FPDiff)
3081     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3082                                     Is64Bit, FPDiff, dl);
3083
3084   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3085   SmallVector<SDValue, 8> MemOpChains;
3086   SDValue StackPtr;
3087
3088   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3089   // of tail call optimization arguments are handle later.
3090   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3091   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3092     // Skip inalloca arguments, they have already been written.
3093     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3094     if (Flags.isInAlloca())
3095       continue;
3096
3097     CCValAssign &VA = ArgLocs[i];
3098     EVT RegVT = VA.getLocVT();
3099     SDValue Arg = OutVals[i];
3100     bool isByVal = Flags.isByVal();
3101
3102     // Promote the value if needed.
3103     switch (VA.getLocInfo()) {
3104     default: llvm_unreachable("Unknown loc info!");
3105     case CCValAssign::Full: break;
3106     case CCValAssign::SExt:
3107       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3108       break;
3109     case CCValAssign::ZExt:
3110       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3111       break;
3112     case CCValAssign::AExt:
3113       if (Arg.getValueType().isVector() &&
3114           Arg.getValueType().getScalarType() == MVT::i1)
3115         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3116       else if (RegVT.is128BitVector()) {
3117         // Special case: passing MMX values in XMM registers.
3118         Arg = DAG.getBitcast(MVT::i64, Arg);
3119         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3120         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3121       } else
3122         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3123       break;
3124     case CCValAssign::BCvt:
3125       Arg = DAG.getBitcast(RegVT, Arg);
3126       break;
3127     case CCValAssign::Indirect: {
3128       // Store the argument.
3129       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3130       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3131       Chain = DAG.getStore(
3132           Chain, dl, Arg, SpillSlot,
3133           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3134           false, false, 0);
3135       Arg = SpillSlot;
3136       break;
3137     }
3138     }
3139
3140     if (VA.isRegLoc()) {
3141       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3142       if (isVarArg && IsWin64) {
3143         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3144         // shadow reg if callee is a varargs function.
3145         unsigned ShadowReg = 0;
3146         switch (VA.getLocReg()) {
3147         case X86::XMM0: ShadowReg = X86::RCX; break;
3148         case X86::XMM1: ShadowReg = X86::RDX; break;
3149         case X86::XMM2: ShadowReg = X86::R8; break;
3150         case X86::XMM3: ShadowReg = X86::R9; break;
3151         }
3152         if (ShadowReg)
3153           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3154       }
3155     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3156       assert(VA.isMemLoc());
3157       if (!StackPtr.getNode())
3158         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3159                                       getPointerTy(DAG.getDataLayout()));
3160       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3161                                              dl, DAG, VA, Flags));
3162     }
3163   }
3164
3165   if (!MemOpChains.empty())
3166     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3167
3168   if (Subtarget->isPICStyleGOT()) {
3169     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3170     // GOT pointer.
3171     if (!isTailCall) {
3172       RegsToPass.push_back(std::make_pair(
3173           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3174                                           getPointerTy(DAG.getDataLayout()))));
3175     } else {
3176       // If we are tail calling and generating PIC/GOT style code load the
3177       // address of the callee into ECX. The value in ecx is used as target of
3178       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3179       // for tail calls on PIC/GOT architectures. Normally we would just put the
3180       // address of GOT into ebx and then call target@PLT. But for tail calls
3181       // ebx would be restored (since ebx is callee saved) before jumping to the
3182       // target@PLT.
3183
3184       // Note: The actual moving to ECX is done further down.
3185       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3186       if (G && !G->getGlobal()->hasLocalLinkage() &&
3187           G->getGlobal()->hasDefaultVisibility())
3188         Callee = LowerGlobalAddress(Callee, DAG);
3189       else if (isa<ExternalSymbolSDNode>(Callee))
3190         Callee = LowerExternalSymbol(Callee, DAG);
3191     }
3192   }
3193
3194   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3195     // From AMD64 ABI document:
3196     // For calls that may call functions that use varargs or stdargs
3197     // (prototype-less calls or calls to functions containing ellipsis (...) in
3198     // the declaration) %al is used as hidden argument to specify the number
3199     // of SSE registers used. The contents of %al do not need to match exactly
3200     // the number of registers, but must be an ubound on the number of SSE
3201     // registers used and is in the range 0 - 8 inclusive.
3202
3203     // Count the number of XMM registers allocated.
3204     static const MCPhysReg XMMArgRegs[] = {
3205       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3206       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3207     };
3208     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3209     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3210            && "SSE registers cannot be used when SSE is disabled");
3211
3212     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3213                                         DAG.getConstant(NumXMMRegs, dl,
3214                                                         MVT::i8)));
3215   }
3216
3217   if (isVarArg && IsMustTail) {
3218     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3219     for (const auto &F : Forwards) {
3220       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3221       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3222     }
3223   }
3224
3225   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3226   // don't need this because the eligibility check rejects calls that require
3227   // shuffling arguments passed in memory.
3228   if (!IsSibcall && isTailCall) {
3229     // Force all the incoming stack arguments to be loaded from the stack
3230     // before any new outgoing arguments are stored to the stack, because the
3231     // outgoing stack slots may alias the incoming argument stack slots, and
3232     // the alias isn't otherwise explicit. This is slightly more conservative
3233     // than necessary, because it means that each store effectively depends
3234     // on every argument instead of just those arguments it would clobber.
3235     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3236
3237     SmallVector<SDValue, 8> MemOpChains2;
3238     SDValue FIN;
3239     int FI = 0;
3240     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3241       CCValAssign &VA = ArgLocs[i];
3242       if (VA.isRegLoc())
3243         continue;
3244       assert(VA.isMemLoc());
3245       SDValue Arg = OutVals[i];
3246       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3247       // Skip inalloca arguments.  They don't require any work.
3248       if (Flags.isInAlloca())
3249         continue;
3250       // Create frame index.
3251       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3252       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3253       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3254       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3255
3256       if (Flags.isByVal()) {
3257         // Copy relative to framepointer.
3258         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3259         if (!StackPtr.getNode())
3260           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3261                                         getPointerTy(DAG.getDataLayout()));
3262         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3263                              StackPtr, Source);
3264
3265         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3266                                                          ArgChain,
3267                                                          Flags, DAG, dl));
3268       } else {
3269         // Store relative to framepointer.
3270         MemOpChains2.push_back(DAG.getStore(
3271             ArgChain, dl, Arg, FIN,
3272             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3273             false, false, 0));
3274       }
3275     }
3276
3277     if (!MemOpChains2.empty())
3278       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3279
3280     // Store the return address to the appropriate stack slot.
3281     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3282                                      getPointerTy(DAG.getDataLayout()),
3283                                      RegInfo->getSlotSize(), FPDiff, dl);
3284   }
3285
3286   // Build a sequence of copy-to-reg nodes chained together with token chain
3287   // and flag operands which copy the outgoing args into registers.
3288   SDValue InFlag;
3289   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3290     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3291                              RegsToPass[i].second, InFlag);
3292     InFlag = Chain.getValue(1);
3293   }
3294
3295   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3296     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3297     // In the 64-bit large code model, we have to make all calls
3298     // through a register, since the call instruction's 32-bit
3299     // pc-relative offset may not be large enough to hold the whole
3300     // address.
3301   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3302     // If the callee is a GlobalAddress node (quite common, every direct call
3303     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3304     // it.
3305     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3306
3307     // We should use extra load for direct calls to dllimported functions in
3308     // non-JIT mode.
3309     const GlobalValue *GV = G->getGlobal();
3310     if (!GV->hasDLLImportStorageClass()) {
3311       unsigned char OpFlags = 0;
3312       bool ExtraLoad = false;
3313       unsigned WrapperKind = ISD::DELETED_NODE;
3314
3315       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3316       // external symbols most go through the PLT in PIC mode.  If the symbol
3317       // has hidden or protected visibility, or if it is static or local, then
3318       // we don't need to use the PLT - we can directly call it.
3319       if (Subtarget->isTargetELF() &&
3320           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3321           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3322         OpFlags = X86II::MO_PLT;
3323       } else if (Subtarget->isPICStyleStubAny() &&
3324                  !GV->isStrongDefinitionForLinker() &&
3325                  (!Subtarget->getTargetTriple().isMacOSX() ||
3326                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3327         // PC-relative references to external symbols should go through $stub,
3328         // unless we're building with the leopard linker or later, which
3329         // automatically synthesizes these stubs.
3330         OpFlags = X86II::MO_DARWIN_STUB;
3331       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3332                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3333         // If the function is marked as non-lazy, generate an indirect call
3334         // which loads from the GOT directly. This avoids runtime overhead
3335         // at the cost of eager binding (and one extra byte of encoding).
3336         OpFlags = X86II::MO_GOTPCREL;
3337         WrapperKind = X86ISD::WrapperRIP;
3338         ExtraLoad = true;
3339       }
3340
3341       Callee = DAG.getTargetGlobalAddress(
3342           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3343
3344       // Add a wrapper if needed.
3345       if (WrapperKind != ISD::DELETED_NODE)
3346         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3347                              getPointerTy(DAG.getDataLayout()), Callee);
3348       // Add extra indirection if needed.
3349       if (ExtraLoad)
3350         Callee = DAG.getLoad(
3351             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3352             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3353             false, 0);
3354     }
3355   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3356     unsigned char OpFlags = 0;
3357
3358     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3359     // external symbols should go through the PLT.
3360     if (Subtarget->isTargetELF() &&
3361         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3362       OpFlags = X86II::MO_PLT;
3363     } else if (Subtarget->isPICStyleStubAny() &&
3364                (!Subtarget->getTargetTriple().isMacOSX() ||
3365                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3366       // PC-relative references to external symbols should go through $stub,
3367       // unless we're building with the leopard linker or later, which
3368       // automatically synthesizes these stubs.
3369       OpFlags = X86II::MO_DARWIN_STUB;
3370     }
3371
3372     Callee = DAG.getTargetExternalSymbol(
3373         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3374   } else if (Subtarget->isTarget64BitILP32() &&
3375              Callee->getValueType(0) == MVT::i32) {
3376     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3377     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3378   }
3379
3380   // Returns a chain & a flag for retval copy to use.
3381   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3382   SmallVector<SDValue, 8> Ops;
3383
3384   if (!IsSibcall && isTailCall) {
3385     Chain = DAG.getCALLSEQ_END(Chain,
3386                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3387                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3388     InFlag = Chain.getValue(1);
3389   }
3390
3391   Ops.push_back(Chain);
3392   Ops.push_back(Callee);
3393
3394   if (isTailCall)
3395     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3396
3397   // Add argument registers to the end of the list so that they are known live
3398   // into the call.
3399   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3400     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3401                                   RegsToPass[i].second.getValueType()));
3402
3403   // Add a register mask operand representing the call-preserved registers.
3404   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3405   assert(Mask && "Missing call preserved mask for calling convention");
3406
3407   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3408   // the function clobbers all registers. If an exception is thrown, the runtime
3409   // will not restore CSRs.
3410   // FIXME: Model this more precisely so that we can register allocate across
3411   // the normal edge and spill and fill across the exceptional edge.
3412   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3413     const Function *CallerFn = MF.getFunction();
3414     EHPersonality Pers =
3415         CallerFn->hasPersonalityFn()
3416             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3417             : EHPersonality::Unknown;
3418     if (isMSVCEHPersonality(Pers))
3419       Mask = RegInfo->getNoPreservedMask();
3420   }
3421
3422   Ops.push_back(DAG.getRegisterMask(Mask));
3423
3424   if (InFlag.getNode())
3425     Ops.push_back(InFlag);
3426
3427   if (isTailCall) {
3428     // We used to do:
3429     //// If this is the first return lowered for this function, add the regs
3430     //// to the liveout set for the function.
3431     // This isn't right, although it's probably harmless on x86; liveouts
3432     // should be computed from returns not tail calls.  Consider a void
3433     // function making a tail call to a function returning int.
3434     MF.getFrameInfo()->setHasTailCall();
3435     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3436   }
3437
3438   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3439   InFlag = Chain.getValue(1);
3440
3441   // Create the CALLSEQ_END node.
3442   unsigned NumBytesForCalleeToPop;
3443   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3444                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3445     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3446   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3447            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3448            SR == StackStructReturn)
3449     // If this is a call to a struct-return function, the callee
3450     // pops the hidden struct pointer, so we have to push it back.
3451     // This is common for Darwin/X86, Linux & Mingw32 targets.
3452     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3453     NumBytesForCalleeToPop = 4;
3454   else
3455     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3456
3457   // Returns a flag for retval copy to use.
3458   if (!IsSibcall) {
3459     Chain = DAG.getCALLSEQ_END(Chain,
3460                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3461                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3462                                                      true),
3463                                InFlag, dl);
3464     InFlag = Chain.getValue(1);
3465   }
3466
3467   if (Subtarget->isTargetWin64() && CLI.CS) {
3468     // Look for a call followed by unreachable. On Win64, we need to ensure that
3469     // the call does not accidentally fall through to something that looks like
3470     // an epilogue. We do this by inserting a DEBUGTRAP, which lowers to int3,
3471     // which is what MSVC emits after noreturn calls.
3472     if (isCallFollowedByUnreachable(*CLI.CS))
3473       Chain = DAG.getNode(ISD::DEBUGTRAP, dl, MVT::Other, Chain);
3474   }
3475
3476   // Handle result values, copying them out of physregs into vregs that we
3477   // return.
3478   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3479                          Ins, dl, DAG, InVals);
3480 }
3481
3482 //===----------------------------------------------------------------------===//
3483 //                Fast Calling Convention (tail call) implementation
3484 //===----------------------------------------------------------------------===//
3485
3486 //  Like std call, callee cleans arguments, convention except that ECX is
3487 //  reserved for storing the tail called function address. Only 2 registers are
3488 //  free for argument passing (inreg). Tail call optimization is performed
3489 //  provided:
3490 //                * tailcallopt is enabled
3491 //                * caller/callee are fastcc
3492 //  On X86_64 architecture with GOT-style position independent code only local
3493 //  (within module) calls are supported at the moment.
3494 //  To keep the stack aligned according to platform abi the function
3495 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3496 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3497 //  If a tail called function callee has more arguments than the caller the
3498 //  caller needs to make sure that there is room to move the RETADDR to. This is
3499 //  achieved by reserving an area the size of the argument delta right after the
3500 //  original RETADDR, but before the saved framepointer or the spilled registers
3501 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3502 //  stack layout:
3503 //    arg1
3504 //    arg2
3505 //    RETADDR
3506 //    [ new RETADDR
3507 //      move area ]
3508 //    (possible EBP)
3509 //    ESI
3510 //    EDI
3511 //    local1 ..
3512
3513 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3514 /// requirement.
3515 unsigned
3516 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3517                                                SelectionDAG& DAG) const {
3518   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3519   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3520   unsigned StackAlignment = TFI.getStackAlignment();
3521   uint64_t AlignMask = StackAlignment - 1;
3522   int64_t Offset = StackSize;
3523   unsigned SlotSize = RegInfo->getSlotSize();
3524   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3525     // Number smaller than 12 so just add the difference.
3526     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3527   } else {
3528     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3529     Offset = ((~AlignMask) & Offset) + StackAlignment +
3530       (StackAlignment-SlotSize);
3531   }
3532   return Offset;
3533 }
3534
3535 /// Return true if the given stack call argument is already available in the
3536 /// same position (relatively) of the caller's incoming argument stack.
3537 static
3538 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3539                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3540                          const X86InstrInfo *TII) {
3541   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3542   int FI = INT_MAX;
3543   if (Arg.getOpcode() == ISD::CopyFromReg) {
3544     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3545     if (!TargetRegisterInfo::isVirtualRegister(VR))
3546       return false;
3547     MachineInstr *Def = MRI->getVRegDef(VR);
3548     if (!Def)
3549       return false;
3550     if (!Flags.isByVal()) {
3551       if (!TII->isLoadFromStackSlot(Def, FI))
3552         return false;
3553     } else {
3554       unsigned Opcode = Def->getOpcode();
3555       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3556            Opcode == X86::LEA64_32r) &&
3557           Def->getOperand(1).isFI()) {
3558         FI = Def->getOperand(1).getIndex();
3559         Bytes = Flags.getByValSize();
3560       } else
3561         return false;
3562     }
3563   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3564     if (Flags.isByVal())
3565       // ByVal argument is passed in as a pointer but it's now being
3566       // dereferenced. e.g.
3567       // define @foo(%struct.X* %A) {
3568       //   tail call @bar(%struct.X* byval %A)
3569       // }
3570       return false;
3571     SDValue Ptr = Ld->getBasePtr();
3572     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3573     if (!FINode)
3574       return false;
3575     FI = FINode->getIndex();
3576   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3577     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3578     FI = FINode->getIndex();
3579     Bytes = Flags.getByValSize();
3580   } else
3581     return false;
3582
3583   assert(FI != INT_MAX);
3584   if (!MFI->isFixedObjectIndex(FI))
3585     return false;
3586   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3587 }
3588
3589 /// Check whether the call is eligible for tail call optimization. Targets
3590 /// that want to do tail call optimization should implement this function.
3591 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3592     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3593     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3594     const SmallVectorImpl<ISD::OutputArg> &Outs,
3595     const SmallVectorImpl<SDValue> &OutVals,
3596     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3597   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3598     return false;
3599
3600   // If -tailcallopt is specified, make fastcc functions tail-callable.
3601   const MachineFunction &MF = DAG.getMachineFunction();
3602   const Function *CallerF = MF.getFunction();
3603
3604   // If the function return type is x86_fp80 and the callee return type is not,
3605   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3606   // perform a tailcall optimization here.
3607   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3608     return false;
3609
3610   CallingConv::ID CallerCC = CallerF->getCallingConv();
3611   bool CCMatch = CallerCC == CalleeCC;
3612   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3613   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3614
3615   // Win64 functions have extra shadow space for argument homing. Don't do the
3616   // sibcall if the caller and callee have mismatched expectations for this
3617   // space.
3618   if (IsCalleeWin64 != IsCallerWin64)
3619     return false;
3620
3621   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3622     if (IsTailCallConvention(CalleeCC) && CCMatch)
3623       return true;
3624     return false;
3625   }
3626
3627   // Look for obvious safe cases to perform tail call optimization that do not
3628   // require ABI changes. This is what gcc calls sibcall.
3629
3630   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3631   // emit a special epilogue.
3632   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3633   if (RegInfo->needsStackRealignment(MF))
3634     return false;
3635
3636   // Also avoid sibcall optimization if either caller or callee uses struct
3637   // return semantics.
3638   if (isCalleeStructRet || isCallerStructRet)
3639     return false;
3640
3641   // An stdcall/thiscall caller is expected to clean up its arguments; the
3642   // callee isn't going to do that.
3643   // FIXME: this is more restrictive than needed. We could produce a tailcall
3644   // when the stack adjustment matches. For example, with a thiscall that takes
3645   // only one argument.
3646   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3647                    CallerCC == CallingConv::X86_ThisCall))
3648     return false;
3649
3650   // Do not sibcall optimize vararg calls unless all arguments are passed via
3651   // registers.
3652   if (isVarArg && !Outs.empty()) {
3653
3654     // Optimizing for varargs on Win64 is unlikely to be safe without
3655     // additional testing.
3656     if (IsCalleeWin64 || IsCallerWin64)
3657       return false;
3658
3659     SmallVector<CCValAssign, 16> ArgLocs;
3660     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3661                    *DAG.getContext());
3662
3663     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3664     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3665       if (!ArgLocs[i].isRegLoc())
3666         return false;
3667   }
3668
3669   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3670   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3671   // this into a sibcall.
3672   bool Unused = false;
3673   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3674     if (!Ins[i].Used) {
3675       Unused = true;
3676       break;
3677     }
3678   }
3679   if (Unused) {
3680     SmallVector<CCValAssign, 16> RVLocs;
3681     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3682                    *DAG.getContext());
3683     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3684     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3685       CCValAssign &VA = RVLocs[i];
3686       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3687         return false;
3688     }
3689   }
3690
3691   // If the calling conventions do not match, then we'd better make sure the
3692   // results are returned in the same way as what the caller expects.
3693   if (!CCMatch) {
3694     SmallVector<CCValAssign, 16> RVLocs1;
3695     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3696                     *DAG.getContext());
3697     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3698
3699     SmallVector<CCValAssign, 16> RVLocs2;
3700     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3701                     *DAG.getContext());
3702     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3703
3704     if (RVLocs1.size() != RVLocs2.size())
3705       return false;
3706     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3707       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3708         return false;
3709       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3710         return false;
3711       if (RVLocs1[i].isRegLoc()) {
3712         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3713           return false;
3714       } else {
3715         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3716           return false;
3717       }
3718     }
3719   }
3720
3721   // If the callee takes no arguments then go on to check the results of the
3722   // call.
3723   if (!Outs.empty()) {
3724     // Check if stack adjustment is needed. For now, do not do this if any
3725     // argument is passed on the stack.
3726     SmallVector<CCValAssign, 16> ArgLocs;
3727     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3728                    *DAG.getContext());
3729
3730     // Allocate shadow area for Win64
3731     if (IsCalleeWin64)
3732       CCInfo.AllocateStack(32, 8);
3733
3734     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3735     if (CCInfo.getNextStackOffset()) {
3736       MachineFunction &MF = DAG.getMachineFunction();
3737       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3738         return false;
3739
3740       // Check if the arguments are already laid out in the right way as
3741       // the caller's fixed stack objects.
3742       MachineFrameInfo *MFI = MF.getFrameInfo();
3743       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3744       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3745       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3746         CCValAssign &VA = ArgLocs[i];
3747         SDValue Arg = OutVals[i];
3748         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3749         if (VA.getLocInfo() == CCValAssign::Indirect)
3750           return false;
3751         if (!VA.isRegLoc()) {
3752           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3753                                    MFI, MRI, TII))
3754             return false;
3755         }
3756       }
3757     }
3758
3759     // If the tailcall address may be in a register, then make sure it's
3760     // possible to register allocate for it. In 32-bit, the call address can
3761     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3762     // callee-saved registers are restored. These happen to be the same
3763     // registers used to pass 'inreg' arguments so watch out for those.
3764     if (!Subtarget->is64Bit() &&
3765         ((!isa<GlobalAddressSDNode>(Callee) &&
3766           !isa<ExternalSymbolSDNode>(Callee)) ||
3767          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3768       unsigned NumInRegs = 0;
3769       // In PIC we need an extra register to formulate the address computation
3770       // for the callee.
3771       unsigned MaxInRegs =
3772         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3773
3774       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3775         CCValAssign &VA = ArgLocs[i];
3776         if (!VA.isRegLoc())
3777           continue;
3778         unsigned Reg = VA.getLocReg();
3779         switch (Reg) {
3780         default: break;
3781         case X86::EAX: case X86::EDX: case X86::ECX:
3782           if (++NumInRegs == MaxInRegs)
3783             return false;
3784           break;
3785         }
3786       }
3787     }
3788   }
3789
3790   return true;
3791 }
3792
3793 FastISel *
3794 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3795                                   const TargetLibraryInfo *libInfo) const {
3796   return X86::createFastISel(funcInfo, libInfo);
3797 }
3798
3799 //===----------------------------------------------------------------------===//
3800 //                           Other Lowering Hooks
3801 //===----------------------------------------------------------------------===//
3802
3803 static bool MayFoldLoad(SDValue Op) {
3804   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3805 }
3806
3807 static bool MayFoldIntoStore(SDValue Op) {
3808   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3809 }
3810
3811 static bool isTargetShuffle(unsigned Opcode) {
3812   switch(Opcode) {
3813   default: return false;
3814   case X86ISD::BLENDI:
3815   case X86ISD::PSHUFB:
3816   case X86ISD::PSHUFD:
3817   case X86ISD::PSHUFHW:
3818   case X86ISD::PSHUFLW:
3819   case X86ISD::SHUFP:
3820   case X86ISD::PALIGNR:
3821   case X86ISD::MOVLHPS:
3822   case X86ISD::MOVLHPD:
3823   case X86ISD::MOVHLPS:
3824   case X86ISD::MOVLPS:
3825   case X86ISD::MOVLPD:
3826   case X86ISD::MOVSHDUP:
3827   case X86ISD::MOVSLDUP:
3828   case X86ISD::MOVDDUP:
3829   case X86ISD::MOVSS:
3830   case X86ISD::MOVSD:
3831   case X86ISD::UNPCKL:
3832   case X86ISD::UNPCKH:
3833   case X86ISD::VPERMILPI:
3834   case X86ISD::VPERM2X128:
3835   case X86ISD::VPERMI:
3836   case X86ISD::VPERMV:
3837   case X86ISD::VPERMV3:
3838     return true;
3839   }
3840 }
3841
3842 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3843                                     SDValue V1, unsigned TargetMask,
3844                                     SelectionDAG &DAG) {
3845   switch(Opc) {
3846   default: llvm_unreachable("Unknown x86 shuffle node");
3847   case X86ISD::PSHUFD:
3848   case X86ISD::PSHUFHW:
3849   case X86ISD::PSHUFLW:
3850   case X86ISD::VPERMILPI:
3851   case X86ISD::VPERMI:
3852     return DAG.getNode(Opc, dl, VT, V1,
3853                        DAG.getConstant(TargetMask, dl, MVT::i8));
3854   }
3855 }
3856
3857 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3858                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3859   switch(Opc) {
3860   default: llvm_unreachable("Unknown x86 shuffle node");
3861   case X86ISD::MOVLHPS:
3862   case X86ISD::MOVLHPD:
3863   case X86ISD::MOVHLPS:
3864   case X86ISD::MOVLPS:
3865   case X86ISD::MOVLPD:
3866   case X86ISD::MOVSS:
3867   case X86ISD::MOVSD:
3868   case X86ISD::UNPCKL:
3869   case X86ISD::UNPCKH:
3870     return DAG.getNode(Opc, dl, VT, V1, V2);
3871   }
3872 }
3873
3874 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3875   MachineFunction &MF = DAG.getMachineFunction();
3876   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3877   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3878   int ReturnAddrIndex = FuncInfo->getRAIndex();
3879
3880   if (ReturnAddrIndex == 0) {
3881     // Set up a frame object for the return address.
3882     unsigned SlotSize = RegInfo->getSlotSize();
3883     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3884                                                            -(int64_t)SlotSize,
3885                                                            false);
3886     FuncInfo->setRAIndex(ReturnAddrIndex);
3887   }
3888
3889   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3890 }
3891
3892 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3893                                        bool hasSymbolicDisplacement) {
3894   // Offset should fit into 32 bit immediate field.
3895   if (!isInt<32>(Offset))
3896     return false;
3897
3898   // If we don't have a symbolic displacement - we don't have any extra
3899   // restrictions.
3900   if (!hasSymbolicDisplacement)
3901     return true;
3902
3903   // FIXME: Some tweaks might be needed for medium code model.
3904   if (M != CodeModel::Small && M != CodeModel::Kernel)
3905     return false;
3906
3907   // For small code model we assume that latest object is 16MB before end of 31
3908   // bits boundary. We may also accept pretty large negative constants knowing
3909   // that all objects are in the positive half of address space.
3910   if (M == CodeModel::Small && Offset < 16*1024*1024)
3911     return true;
3912
3913   // For kernel code model we know that all object resist in the negative half
3914   // of 32bits address space. We may not accept negative offsets, since they may
3915   // be just off and we may accept pretty large positive ones.
3916   if (M == CodeModel::Kernel && Offset >= 0)
3917     return true;
3918
3919   return false;
3920 }
3921
3922 /// Determines whether the callee is required to pop its own arguments.
3923 /// Callee pop is necessary to support tail calls.
3924 bool X86::isCalleePop(CallingConv::ID CallingConv,
3925                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3926
3927   if (IsTailCallConvention(CallingConv))
3928     return IsVarArg ? false : TailCallOpt;
3929
3930   switch (CallingConv) {
3931   default:
3932     return false;
3933   case CallingConv::X86_StdCall:
3934   case CallingConv::X86_FastCall:
3935   case CallingConv::X86_ThisCall:
3936     return !is64Bit;
3937   }
3938 }
3939
3940 /// \brief Return true if the condition is an unsigned comparison operation.
3941 static bool isX86CCUnsigned(unsigned X86CC) {
3942   switch (X86CC) {
3943   default: llvm_unreachable("Invalid integer condition!");
3944   case X86::COND_E:     return true;
3945   case X86::COND_G:     return false;
3946   case X86::COND_GE:    return false;
3947   case X86::COND_L:     return false;
3948   case X86::COND_LE:    return false;
3949   case X86::COND_NE:    return true;
3950   case X86::COND_B:     return true;
3951   case X86::COND_A:     return true;
3952   case X86::COND_BE:    return true;
3953   case X86::COND_AE:    return true;
3954   }
3955   llvm_unreachable("covered switch fell through?!");
3956 }
3957
3958 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3959 /// condition code, returning the condition code and the LHS/RHS of the
3960 /// comparison to make.
3961 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3962                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3963   if (!isFP) {
3964     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3965       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3966         // X > -1   -> X == 0, jump !sign.
3967         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3968         return X86::COND_NS;
3969       }
3970       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3971         // X < 0   -> X == 0, jump on sign.
3972         return X86::COND_S;
3973       }
3974       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3975         // X < 1   -> X <= 0
3976         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3977         return X86::COND_LE;
3978       }
3979     }
3980
3981     switch (SetCCOpcode) {
3982     default: llvm_unreachable("Invalid integer condition!");
3983     case ISD::SETEQ:  return X86::COND_E;
3984     case ISD::SETGT:  return X86::COND_G;
3985     case ISD::SETGE:  return X86::COND_GE;
3986     case ISD::SETLT:  return X86::COND_L;
3987     case ISD::SETLE:  return X86::COND_LE;
3988     case ISD::SETNE:  return X86::COND_NE;
3989     case ISD::SETULT: return X86::COND_B;
3990     case ISD::SETUGT: return X86::COND_A;
3991     case ISD::SETULE: return X86::COND_BE;
3992     case ISD::SETUGE: return X86::COND_AE;
3993     }
3994   }
3995
3996   // First determine if it is required or is profitable to flip the operands.
3997
3998   // If LHS is a foldable load, but RHS is not, flip the condition.
3999   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4000       !ISD::isNON_EXTLoad(RHS.getNode())) {
4001     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4002     std::swap(LHS, RHS);
4003   }
4004
4005   switch (SetCCOpcode) {
4006   default: break;
4007   case ISD::SETOLT:
4008   case ISD::SETOLE:
4009   case ISD::SETUGT:
4010   case ISD::SETUGE:
4011     std::swap(LHS, RHS);
4012     break;
4013   }
4014
4015   // On a floating point condition, the flags are set as follows:
4016   // ZF  PF  CF   op
4017   //  0 | 0 | 0 | X > Y
4018   //  0 | 0 | 1 | X < Y
4019   //  1 | 0 | 0 | X == Y
4020   //  1 | 1 | 1 | unordered
4021   switch (SetCCOpcode) {
4022   default: llvm_unreachable("Condcode should be pre-legalized away");
4023   case ISD::SETUEQ:
4024   case ISD::SETEQ:   return X86::COND_E;
4025   case ISD::SETOLT:              // flipped
4026   case ISD::SETOGT:
4027   case ISD::SETGT:   return X86::COND_A;
4028   case ISD::SETOLE:              // flipped
4029   case ISD::SETOGE:
4030   case ISD::SETGE:   return X86::COND_AE;
4031   case ISD::SETUGT:              // flipped
4032   case ISD::SETULT:
4033   case ISD::SETLT:   return X86::COND_B;
4034   case ISD::SETUGE:              // flipped
4035   case ISD::SETULE:
4036   case ISD::SETLE:   return X86::COND_BE;
4037   case ISD::SETONE:
4038   case ISD::SETNE:   return X86::COND_NE;
4039   case ISD::SETUO:   return X86::COND_P;
4040   case ISD::SETO:    return X86::COND_NP;
4041   case ISD::SETOEQ:
4042   case ISD::SETUNE:  return X86::COND_INVALID;
4043   }
4044 }
4045
4046 /// Is there a floating point cmov for the specific X86 condition code?
4047 /// Current x86 isa includes the following FP cmov instructions:
4048 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4049 static bool hasFPCMov(unsigned X86CC) {
4050   switch (X86CC) {
4051   default:
4052     return false;
4053   case X86::COND_B:
4054   case X86::COND_BE:
4055   case X86::COND_E:
4056   case X86::COND_P:
4057   case X86::COND_A:
4058   case X86::COND_AE:
4059   case X86::COND_NE:
4060   case X86::COND_NP:
4061     return true;
4062   }
4063 }
4064
4065 /// Returns true if the target can instruction select the
4066 /// specified FP immediate natively. If false, the legalizer will
4067 /// materialize the FP immediate as a load from a constant pool.
4068 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4069   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4070     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4071       return true;
4072   }
4073   return false;
4074 }
4075
4076 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4077                                               ISD::LoadExtType ExtTy,
4078                                               EVT NewVT) const {
4079   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4080   // relocation target a movq or addq instruction: don't let the load shrink.
4081   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4082   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4083     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4084       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4085   return true;
4086 }
4087
4088 /// \brief Returns true if it is beneficial to convert a load of a constant
4089 /// to just the constant itself.
4090 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4091                                                           Type *Ty) const {
4092   assert(Ty->isIntegerTy());
4093
4094   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4095   if (BitSize == 0 || BitSize > 64)
4096     return false;
4097   return true;
4098 }
4099
4100 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4101                                                 unsigned Index) const {
4102   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4103     return false;
4104
4105   return (Index == 0 || Index == ResVT.getVectorNumElements());
4106 }
4107
4108 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4109   // Speculate cttz only if we can directly use TZCNT.
4110   return Subtarget->hasBMI();
4111 }
4112
4113 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4114   // Speculate ctlz only if we can directly use LZCNT.
4115   return Subtarget->hasLZCNT();
4116 }
4117
4118 /// Return true if every element in Mask, beginning
4119 /// from position Pos and ending in Pos+Size is undef.
4120 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4121   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4122     if (0 <= Mask[i])
4123       return false;
4124   return true;
4125 }
4126
4127 /// Return true if Val is undef or if its value falls within the
4128 /// specified range (L, H].
4129 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4130   return (Val < 0) || (Val >= Low && Val < Hi);
4131 }
4132
4133 /// Val is either less than zero (undef) or equal to the specified value.
4134 static bool isUndefOrEqual(int Val, int CmpVal) {
4135   return (Val < 0 || Val == CmpVal);
4136 }
4137
4138 /// Return true if every element in Mask, beginning
4139 /// from position Pos and ending in Pos+Size, falls within the specified
4140 /// sequential range (Low, Low+Size]. or is undef.
4141 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4142                                        unsigned Pos, unsigned Size, int Low) {
4143   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4144     if (!isUndefOrEqual(Mask[i], Low))
4145       return false;
4146   return true;
4147 }
4148
4149 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4150 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4151 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4152   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4153   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4154     return false;
4155
4156   // The index should be aligned on a vecWidth-bit boundary.
4157   uint64_t Index =
4158     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4159
4160   MVT VT = N->getSimpleValueType(0);
4161   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4162   bool Result = (Index * ElSize) % vecWidth == 0;
4163
4164   return Result;
4165 }
4166
4167 /// Return true if the specified INSERT_SUBVECTOR
4168 /// operand specifies a subvector insert that is suitable for input to
4169 /// insertion of 128 or 256-bit subvectors
4170 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4171   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4172   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4173     return false;
4174   // The index should be aligned on a vecWidth-bit boundary.
4175   uint64_t Index =
4176     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4177
4178   MVT VT = N->getSimpleValueType(0);
4179   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4180   bool Result = (Index * ElSize) % vecWidth == 0;
4181
4182   return Result;
4183 }
4184
4185 bool X86::isVINSERT128Index(SDNode *N) {
4186   return isVINSERTIndex(N, 128);
4187 }
4188
4189 bool X86::isVINSERT256Index(SDNode *N) {
4190   return isVINSERTIndex(N, 256);
4191 }
4192
4193 bool X86::isVEXTRACT128Index(SDNode *N) {
4194   return isVEXTRACTIndex(N, 128);
4195 }
4196
4197 bool X86::isVEXTRACT256Index(SDNode *N) {
4198   return isVEXTRACTIndex(N, 256);
4199 }
4200
4201 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4202   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4203   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4204     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4205
4206   uint64_t Index =
4207     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4208
4209   MVT VecVT = N->getOperand(0).getSimpleValueType();
4210   MVT ElVT = VecVT.getVectorElementType();
4211
4212   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4213   return Index / NumElemsPerChunk;
4214 }
4215
4216 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4217   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4218   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4219     llvm_unreachable("Illegal insert subvector for VINSERT");
4220
4221   uint64_t Index =
4222     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4223
4224   MVT VecVT = N->getSimpleValueType(0);
4225   MVT ElVT = VecVT.getVectorElementType();
4226
4227   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4228   return Index / NumElemsPerChunk;
4229 }
4230
4231 /// Return the appropriate immediate to extract the specified
4232 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4233 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4234   return getExtractVEXTRACTImmediate(N, 128);
4235 }
4236
4237 /// Return the appropriate immediate to extract the specified
4238 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4239 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4240   return getExtractVEXTRACTImmediate(N, 256);
4241 }
4242
4243 /// Return the appropriate immediate to insert at the specified
4244 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4245 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4246   return getInsertVINSERTImmediate(N, 128);
4247 }
4248
4249 /// Return the appropriate immediate to insert at the specified
4250 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4251 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4252   return getInsertVINSERTImmediate(N, 256);
4253 }
4254
4255 /// Returns true if Elt is a constant integer zero
4256 static bool isZero(SDValue V) {
4257   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4258   return C && C->isNullValue();
4259 }
4260
4261 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4262 bool X86::isZeroNode(SDValue Elt) {
4263   if (isZero(Elt))
4264     return true;
4265   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4266     return CFP->getValueAPF().isPosZero();
4267   return false;
4268 }
4269
4270 /// Returns a vector of specified type with all zero elements.
4271 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4272                              SelectionDAG &DAG, SDLoc dl) {
4273   assert(VT.isVector() && "Expected a vector type");
4274
4275   // Always build SSE zero vectors as <4 x i32> bitcasted
4276   // to their dest type. This ensures they get CSE'd.
4277   SDValue Vec;
4278   if (VT.is128BitVector()) {  // SSE
4279     if (Subtarget->hasSSE2()) {  // SSE2
4280       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4281       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4282     } else { // SSE1
4283       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4284       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4285     }
4286   } else if (VT.is256BitVector()) { // AVX
4287     if (Subtarget->hasInt256()) { // AVX2
4288       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4289       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4290       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4291     } else {
4292       // 256-bit logic and arithmetic instructions in AVX are all
4293       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4294       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4295       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4296       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4297     }
4298   } else if (VT.is512BitVector()) { // AVX-512
4299       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4300       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4301                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4302       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4303   } else if (VT.getScalarType() == MVT::i1) {
4304
4305     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4306             && "Unexpected vector type");
4307     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4308             && "Unexpected vector type");
4309     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4310     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4311     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4312   } else
4313     llvm_unreachable("Unexpected vector type");
4314
4315   return DAG.getBitcast(VT, Vec);
4316 }
4317
4318 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4319                                 SelectionDAG &DAG, SDLoc dl,
4320                                 unsigned vectorWidth) {
4321   assert((vectorWidth == 128 || vectorWidth == 256) &&
4322          "Unsupported vector width");
4323   EVT VT = Vec.getValueType();
4324   EVT ElVT = VT.getVectorElementType();
4325   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4326   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4327                                   VT.getVectorNumElements()/Factor);
4328
4329   // Extract from UNDEF is UNDEF.
4330   if (Vec.getOpcode() == ISD::UNDEF)
4331     return DAG.getUNDEF(ResultVT);
4332
4333   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4334   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4335
4336   // This is the index of the first element of the vectorWidth-bit chunk
4337   // we want.
4338   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4339                                * ElemsPerChunk);
4340
4341   // If the input is a buildvector just emit a smaller one.
4342   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4343     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4344                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4345                                     ElemsPerChunk));
4346
4347   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4348   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4349 }
4350
4351 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4352 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4353 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4354 /// instructions or a simple subregister reference. Idx is an index in the
4355 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4356 /// lowering EXTRACT_VECTOR_ELT operations easier.
4357 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4358                                    SelectionDAG &DAG, SDLoc dl) {
4359   assert((Vec.getValueType().is256BitVector() ||
4360           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4361   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4362 }
4363
4364 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4365 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4366                                    SelectionDAG &DAG, SDLoc dl) {
4367   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4368   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4369 }
4370
4371 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4372                                unsigned IdxVal, SelectionDAG &DAG,
4373                                SDLoc dl, unsigned vectorWidth) {
4374   assert((vectorWidth == 128 || vectorWidth == 256) &&
4375          "Unsupported vector width");
4376   // Inserting UNDEF is Result
4377   if (Vec.getOpcode() == ISD::UNDEF)
4378     return Result;
4379   EVT VT = Vec.getValueType();
4380   EVT ElVT = VT.getVectorElementType();
4381   EVT ResultVT = Result.getValueType();
4382
4383   // Insert the relevant vectorWidth bits.
4384   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4385
4386   // This is the index of the first element of the vectorWidth-bit chunk
4387   // we want.
4388   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4389                                * ElemsPerChunk);
4390
4391   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4392   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4393 }
4394
4395 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4396 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4397 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4398 /// simple superregister reference.  Idx is an index in the 128 bits
4399 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4400 /// lowering INSERT_VECTOR_ELT operations easier.
4401 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4402                                   SelectionDAG &DAG, SDLoc dl) {
4403   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4404
4405   // For insertion into the zero index (low half) of a 256-bit vector, it is
4406   // more efficient to generate a blend with immediate instead of an insert*128.
4407   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4408   // extend the subvector to the size of the result vector. Make sure that
4409   // we are not recursing on that node by checking for undef here.
4410   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4411       Result.getOpcode() != ISD::UNDEF) {
4412     EVT ResultVT = Result.getValueType();
4413     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4414     SDValue Undef = DAG.getUNDEF(ResultVT);
4415     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4416                                  Vec, ZeroIndex);
4417
4418     // The blend instruction, and therefore its mask, depend on the data type.
4419     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4420     if (ScalarType.isFloatingPoint()) {
4421       // Choose either vblendps (float) or vblendpd (double).
4422       unsigned ScalarSize = ScalarType.getSizeInBits();
4423       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4424       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4425       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4426       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4427     }
4428
4429     const X86Subtarget &Subtarget =
4430     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4431
4432     // AVX2 is needed for 256-bit integer blend support.
4433     // Integers must be cast to 32-bit because there is only vpblendd;
4434     // vpblendw can't be used for this because it has a handicapped mask.
4435
4436     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4437     // is still more efficient than using the wrong domain vinsertf128 that
4438     // will be created by InsertSubVector().
4439     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4440
4441     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4442     Vec256 = DAG.getBitcast(CastVT, Vec256);
4443     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4444     return DAG.getBitcast(ResultVT, Vec256);
4445   }
4446
4447   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4448 }
4449
4450 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4451                                   SelectionDAG &DAG, SDLoc dl) {
4452   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4453   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4454 }
4455
4456 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4457 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4458 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4459 /// large BUILD_VECTORS.
4460 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4461                                    unsigned NumElems, SelectionDAG &DAG,
4462                                    SDLoc dl) {
4463   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4464   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4465 }
4466
4467 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4468                                    unsigned NumElems, SelectionDAG &DAG,
4469                                    SDLoc dl) {
4470   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4471   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4472 }
4473
4474 /// Returns a vector of specified type with all bits set.
4475 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4476 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4477 /// Then bitcast to their original type, ensuring they get CSE'd.
4478 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4479                              SelectionDAG &DAG, SDLoc dl) {
4480   assert(VT.isVector() && "Expected a vector type");
4481
4482   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4483   SDValue Vec;
4484   if (VT.is512BitVector()) {
4485     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4486                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4487     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4488   } else if (VT.is256BitVector()) {
4489     if (Subtarget->hasInt256()) { // AVX2
4490       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4491       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4492     } else { // AVX
4493       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4494       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4495     }
4496   } else if (VT.is128BitVector()) {
4497     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4498   } else
4499     llvm_unreachable("Unexpected vector type");
4500
4501   return DAG.getBitcast(VT, Vec);
4502 }
4503
4504 /// Returns a vector_shuffle node for an unpackl operation.
4505 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4506                           SDValue V2) {
4507   unsigned NumElems = VT.getVectorNumElements();
4508   SmallVector<int, 8> Mask;
4509   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4510     Mask.push_back(i);
4511     Mask.push_back(i + NumElems);
4512   }
4513   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4514 }
4515
4516 /// Returns a vector_shuffle node for an unpackh operation.
4517 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4518                           SDValue V2) {
4519   unsigned NumElems = VT.getVectorNumElements();
4520   SmallVector<int, 8> Mask;
4521   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4522     Mask.push_back(i + Half);
4523     Mask.push_back(i + NumElems + Half);
4524   }
4525   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4526 }
4527
4528 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4529 /// This produces a shuffle where the low element of V2 is swizzled into the
4530 /// zero/undef vector, landing at element Idx.
4531 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4532 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4533                                            bool IsZero,
4534                                            const X86Subtarget *Subtarget,
4535                                            SelectionDAG &DAG) {
4536   MVT VT = V2.getSimpleValueType();
4537   SDValue V1 = IsZero
4538     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4539   unsigned NumElems = VT.getVectorNumElements();
4540   SmallVector<int, 16> MaskVec;
4541   for (unsigned i = 0; i != NumElems; ++i)
4542     // If this is the insertion idx, put the low elt of V2 here.
4543     MaskVec.push_back(i == Idx ? NumElems : i);
4544   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4545 }
4546
4547 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4548 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4549 /// uses one source. Note that this will set IsUnary for shuffles which use a
4550 /// single input multiple times, and in those cases it will
4551 /// adjust the mask to only have indices within that single input.
4552 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4553 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4554                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4555   unsigned NumElems = VT.getVectorNumElements();
4556   SDValue ImmN;
4557
4558   IsUnary = false;
4559   bool IsFakeUnary = false;
4560   switch(N->getOpcode()) {
4561   case X86ISD::BLENDI:
4562     ImmN = N->getOperand(N->getNumOperands()-1);
4563     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4564     break;
4565   case X86ISD::SHUFP:
4566     ImmN = N->getOperand(N->getNumOperands()-1);
4567     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4568     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4569     break;
4570   case X86ISD::UNPCKH:
4571     DecodeUNPCKHMask(VT, Mask);
4572     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4573     break;
4574   case X86ISD::UNPCKL:
4575     DecodeUNPCKLMask(VT, Mask);
4576     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4577     break;
4578   case X86ISD::MOVHLPS:
4579     DecodeMOVHLPSMask(NumElems, Mask);
4580     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4581     break;
4582   case X86ISD::MOVLHPS:
4583     DecodeMOVLHPSMask(NumElems, Mask);
4584     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4585     break;
4586   case X86ISD::PALIGNR:
4587     ImmN = N->getOperand(N->getNumOperands()-1);
4588     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4589     break;
4590   case X86ISD::PSHUFD:
4591   case X86ISD::VPERMILPI:
4592     ImmN = N->getOperand(N->getNumOperands()-1);
4593     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4594     IsUnary = true;
4595     break;
4596   case X86ISD::PSHUFHW:
4597     ImmN = N->getOperand(N->getNumOperands()-1);
4598     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4599     IsUnary = true;
4600     break;
4601   case X86ISD::PSHUFLW:
4602     ImmN = N->getOperand(N->getNumOperands()-1);
4603     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4604     IsUnary = true;
4605     break;
4606   case X86ISD::PSHUFB: {
4607     IsUnary = true;
4608     SDValue MaskNode = N->getOperand(1);
4609     while (MaskNode->getOpcode() == ISD::BITCAST)
4610       MaskNode = MaskNode->getOperand(0);
4611
4612     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4613       // If we have a build-vector, then things are easy.
4614       EVT VT = MaskNode.getValueType();
4615       assert(VT.isVector() &&
4616              "Can't produce a non-vector with a build_vector!");
4617       if (!VT.isInteger())
4618         return false;
4619
4620       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4621
4622       SmallVector<uint64_t, 32> RawMask;
4623       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4624         SDValue Op = MaskNode->getOperand(i);
4625         if (Op->getOpcode() == ISD::UNDEF) {
4626           RawMask.push_back((uint64_t)SM_SentinelUndef);
4627           continue;
4628         }
4629         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4630         if (!CN)
4631           return false;
4632         APInt MaskElement = CN->getAPIntValue();
4633
4634         // We now have to decode the element which could be any integer size and
4635         // extract each byte of it.
4636         for (int j = 0; j < NumBytesPerElement; ++j) {
4637           // Note that this is x86 and so always little endian: the low byte is
4638           // the first byte of the mask.
4639           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4640           MaskElement = MaskElement.lshr(8);
4641         }
4642       }
4643       DecodePSHUFBMask(RawMask, Mask);
4644       break;
4645     }
4646
4647     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4648     if (!MaskLoad)
4649       return false;
4650
4651     SDValue Ptr = MaskLoad->getBasePtr();
4652     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4653         Ptr->getOpcode() == X86ISD::WrapperRIP)
4654       Ptr = Ptr->getOperand(0);
4655
4656     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4657     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4658       return false;
4659
4660     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4661       DecodePSHUFBMask(C, Mask);
4662       if (Mask.empty())
4663         return false;
4664       break;
4665     }
4666
4667     return false;
4668   }
4669   case X86ISD::VPERMI:
4670     ImmN = N->getOperand(N->getNumOperands()-1);
4671     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4672     IsUnary = true;
4673     break;
4674   case X86ISD::MOVSS:
4675   case X86ISD::MOVSD:
4676     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4677     break;
4678   case X86ISD::VPERM2X128:
4679     ImmN = N->getOperand(N->getNumOperands()-1);
4680     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4681     if (Mask.empty()) return false;
4682     // Mask only contains negative index if an element is zero.
4683     if (std::any_of(Mask.begin(), Mask.end(),
4684                     [](int M){ return M == SM_SentinelZero; }))
4685       return false;
4686     break;
4687   case X86ISD::MOVSLDUP:
4688     DecodeMOVSLDUPMask(VT, Mask);
4689     IsUnary = true;
4690     break;
4691   case X86ISD::MOVSHDUP:
4692     DecodeMOVSHDUPMask(VT, Mask);
4693     IsUnary = true;
4694     break;
4695   case X86ISD::MOVDDUP:
4696     DecodeMOVDDUPMask(VT, Mask);
4697     IsUnary = true;
4698     break;
4699   case X86ISD::MOVLHPD:
4700   case X86ISD::MOVLPD:
4701   case X86ISD::MOVLPS:
4702     // Not yet implemented
4703     return false;
4704   case X86ISD::VPERMV: {
4705     IsUnary = true;
4706     SDValue MaskNode = N->getOperand(0);
4707     while (MaskNode->getOpcode() == ISD::BITCAST)
4708       MaskNode = MaskNode->getOperand(0);
4709
4710     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4711     SmallVector<uint64_t, 32> RawMask;
4712     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4713       // If we have a build-vector, then things are easy.
4714       assert(MaskNode.getValueType().isInteger() &&
4715              MaskNode.getValueType().getVectorNumElements() ==
4716              VT.getVectorNumElements());
4717
4718       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4719         SDValue Op = MaskNode->getOperand(i);
4720         if (Op->getOpcode() == ISD::UNDEF)
4721           RawMask.push_back((uint64_t)SM_SentinelUndef);
4722         else if (isa<ConstantSDNode>(Op)) {
4723           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4724           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4725         } else
4726           return false;
4727       }
4728       DecodeVPERMVMask(RawMask, Mask);
4729       break;
4730     }
4731     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4732       unsigned NumEltsInMask = MaskNode->getNumOperands();
4733       MaskNode = MaskNode->getOperand(0);
4734       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4735       if (CN) {
4736         APInt MaskEltValue = CN->getAPIntValue();
4737         for (unsigned i = 0; i < NumEltsInMask; ++i)
4738           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4739         DecodeVPERMVMask(RawMask, Mask);
4740         break;
4741       }
4742       // It may be a scalar load
4743     }
4744
4745     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4746     if (!MaskLoad)
4747       return false;
4748
4749     SDValue Ptr = MaskLoad->getBasePtr();
4750     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4751         Ptr->getOpcode() == X86ISD::WrapperRIP)
4752       Ptr = Ptr->getOperand(0);
4753
4754     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4755     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4756       return false;
4757
4758     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4759     if (C) {
4760       DecodeVPERMVMask(C, VT, Mask);
4761       if (Mask.empty())
4762         return false;
4763       break;
4764     }
4765     return false;
4766   }
4767   case X86ISD::VPERMV3: {
4768     IsUnary = false;
4769     SDValue MaskNode = N->getOperand(1);
4770     while (MaskNode->getOpcode() == ISD::BITCAST)
4771       MaskNode = MaskNode->getOperand(1);
4772
4773     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4774       // If we have a build-vector, then things are easy.
4775       assert(MaskNode.getValueType().isInteger() &&
4776              MaskNode.getValueType().getVectorNumElements() ==
4777              VT.getVectorNumElements());
4778
4779       SmallVector<uint64_t, 32> RawMask;
4780       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4781
4782       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4783         SDValue Op = MaskNode->getOperand(i);
4784         if (Op->getOpcode() == ISD::UNDEF)
4785           RawMask.push_back((uint64_t)SM_SentinelUndef);
4786         else {
4787           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4788           if (!CN)
4789             return false;
4790           APInt MaskElement = CN->getAPIntValue();
4791           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4792         }
4793       }
4794       DecodeVPERMV3Mask(RawMask, Mask);
4795       break;
4796     }
4797
4798     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4799     if (!MaskLoad)
4800       return false;
4801
4802     SDValue Ptr = MaskLoad->getBasePtr();
4803     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4804         Ptr->getOpcode() == X86ISD::WrapperRIP)
4805       Ptr = Ptr->getOperand(0);
4806
4807     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4808     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4809       return false;
4810
4811     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4812     if (C) {
4813       DecodeVPERMV3Mask(C, VT, Mask);
4814       if (Mask.empty())
4815         return false;
4816       break;
4817     }
4818     return false;
4819   }
4820   default: llvm_unreachable("unknown target shuffle node");
4821   }
4822
4823   // If we have a fake unary shuffle, the shuffle mask is spread across two
4824   // inputs that are actually the same node. Re-map the mask to always point
4825   // into the first input.
4826   if (IsFakeUnary)
4827     for (int &M : Mask)
4828       if (M >= (int)Mask.size())
4829         M -= Mask.size();
4830
4831   return true;
4832 }
4833
4834 /// Returns the scalar element that will make up the ith
4835 /// element of the result of the vector shuffle.
4836 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4837                                    unsigned Depth) {
4838   if (Depth == 6)
4839     return SDValue();  // Limit search depth.
4840
4841   SDValue V = SDValue(N, 0);
4842   EVT VT = V.getValueType();
4843   unsigned Opcode = V.getOpcode();
4844
4845   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4846   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4847     int Elt = SV->getMaskElt(Index);
4848
4849     if (Elt < 0)
4850       return DAG.getUNDEF(VT.getVectorElementType());
4851
4852     unsigned NumElems = VT.getVectorNumElements();
4853     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4854                                          : SV->getOperand(1);
4855     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4856   }
4857
4858   // Recurse into target specific vector shuffles to find scalars.
4859   if (isTargetShuffle(Opcode)) {
4860     MVT ShufVT = V.getSimpleValueType();
4861     unsigned NumElems = ShufVT.getVectorNumElements();
4862     SmallVector<int, 16> ShuffleMask;
4863     bool IsUnary;
4864
4865     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4866       return SDValue();
4867
4868     int Elt = ShuffleMask[Index];
4869     if (Elt < 0)
4870       return DAG.getUNDEF(ShufVT.getVectorElementType());
4871
4872     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4873                                          : N->getOperand(1);
4874     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4875                                Depth+1);
4876   }
4877
4878   // Actual nodes that may contain scalar elements
4879   if (Opcode == ISD::BITCAST) {
4880     V = V.getOperand(0);
4881     EVT SrcVT = V.getValueType();
4882     unsigned NumElems = VT.getVectorNumElements();
4883
4884     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4885       return SDValue();
4886   }
4887
4888   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4889     return (Index == 0) ? V.getOperand(0)
4890                         : DAG.getUNDEF(VT.getVectorElementType());
4891
4892   if (V.getOpcode() == ISD::BUILD_VECTOR)
4893     return V.getOperand(Index);
4894
4895   return SDValue();
4896 }
4897
4898 /// Custom lower build_vector of v16i8.
4899 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4900                                        unsigned NumNonZero, unsigned NumZero,
4901                                        SelectionDAG &DAG,
4902                                        const X86Subtarget* Subtarget,
4903                                        const TargetLowering &TLI) {
4904   if (NumNonZero > 8)
4905     return SDValue();
4906
4907   SDLoc dl(Op);
4908   SDValue V;
4909   bool First = true;
4910
4911   // SSE4.1 - use PINSRB to insert each byte directly.
4912   if (Subtarget->hasSSE41()) {
4913     for (unsigned i = 0; i < 16; ++i) {
4914       bool isNonZero = (NonZeros & (1 << i)) != 0;
4915       if (isNonZero) {
4916         if (First) {
4917           if (NumZero)
4918             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4919           else
4920             V = DAG.getUNDEF(MVT::v16i8);
4921           First = false;
4922         }
4923         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4924                         MVT::v16i8, V, Op.getOperand(i),
4925                         DAG.getIntPtrConstant(i, dl));
4926       }
4927     }
4928
4929     return V;
4930   }
4931
4932   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4933   for (unsigned i = 0; i < 16; ++i) {
4934     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4935     if (ThisIsNonZero && First) {
4936       if (NumZero)
4937         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4938       else
4939         V = DAG.getUNDEF(MVT::v8i16);
4940       First = false;
4941     }
4942
4943     if ((i & 1) != 0) {
4944       SDValue ThisElt, LastElt;
4945       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4946       if (LastIsNonZero) {
4947         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4948                               MVT::i16, Op.getOperand(i-1));
4949       }
4950       if (ThisIsNonZero) {
4951         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4952         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4953                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4954         if (LastIsNonZero)
4955           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4956       } else
4957         ThisElt = LastElt;
4958
4959       if (ThisElt.getNode())
4960         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4961                         DAG.getIntPtrConstant(i/2, dl));
4962     }
4963   }
4964
4965   return DAG.getBitcast(MVT::v16i8, V);
4966 }
4967
4968 /// Custom lower build_vector of v8i16.
4969 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4970                                      unsigned NumNonZero, unsigned NumZero,
4971                                      SelectionDAG &DAG,
4972                                      const X86Subtarget* Subtarget,
4973                                      const TargetLowering &TLI) {
4974   if (NumNonZero > 4)
4975     return SDValue();
4976
4977   SDLoc dl(Op);
4978   SDValue V;
4979   bool First = true;
4980   for (unsigned i = 0; i < 8; ++i) {
4981     bool isNonZero = (NonZeros & (1 << i)) != 0;
4982     if (isNonZero) {
4983       if (First) {
4984         if (NumZero)
4985           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4986         else
4987           V = DAG.getUNDEF(MVT::v8i16);
4988         First = false;
4989       }
4990       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4991                       MVT::v8i16, V, Op.getOperand(i),
4992                       DAG.getIntPtrConstant(i, dl));
4993     }
4994   }
4995
4996   return V;
4997 }
4998
4999 /// Custom lower build_vector of v4i32 or v4f32.
5000 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5001                                      const X86Subtarget *Subtarget,
5002                                      const TargetLowering &TLI) {
5003   // Find all zeroable elements.
5004   std::bitset<4> Zeroable;
5005   for (int i=0; i < 4; ++i) {
5006     SDValue Elt = Op->getOperand(i);
5007     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5008   }
5009   assert(Zeroable.size() - Zeroable.count() > 1 &&
5010          "We expect at least two non-zero elements!");
5011
5012   // We only know how to deal with build_vector nodes where elements are either
5013   // zeroable or extract_vector_elt with constant index.
5014   SDValue FirstNonZero;
5015   unsigned FirstNonZeroIdx;
5016   for (unsigned i=0; i < 4; ++i) {
5017     if (Zeroable[i])
5018       continue;
5019     SDValue Elt = Op->getOperand(i);
5020     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5021         !isa<ConstantSDNode>(Elt.getOperand(1)))
5022       return SDValue();
5023     // Make sure that this node is extracting from a 128-bit vector.
5024     MVT VT = Elt.getOperand(0).getSimpleValueType();
5025     if (!VT.is128BitVector())
5026       return SDValue();
5027     if (!FirstNonZero.getNode()) {
5028       FirstNonZero = Elt;
5029       FirstNonZeroIdx = i;
5030     }
5031   }
5032
5033   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5034   SDValue V1 = FirstNonZero.getOperand(0);
5035   MVT VT = V1.getSimpleValueType();
5036
5037   // See if this build_vector can be lowered as a blend with zero.
5038   SDValue Elt;
5039   unsigned EltMaskIdx, EltIdx;
5040   int Mask[4];
5041   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5042     if (Zeroable[EltIdx]) {
5043       // The zero vector will be on the right hand side.
5044       Mask[EltIdx] = EltIdx+4;
5045       continue;
5046     }
5047
5048     Elt = Op->getOperand(EltIdx);
5049     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5050     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5051     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5052       break;
5053     Mask[EltIdx] = EltIdx;
5054   }
5055
5056   if (EltIdx == 4) {
5057     // Let the shuffle legalizer deal with blend operations.
5058     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5059     if (V1.getSimpleValueType() != VT)
5060       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5061     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5062   }
5063
5064   // See if we can lower this build_vector to a INSERTPS.
5065   if (!Subtarget->hasSSE41())
5066     return SDValue();
5067
5068   SDValue V2 = Elt.getOperand(0);
5069   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5070     V1 = SDValue();
5071
5072   bool CanFold = true;
5073   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5074     if (Zeroable[i])
5075       continue;
5076
5077     SDValue Current = Op->getOperand(i);
5078     SDValue SrcVector = Current->getOperand(0);
5079     if (!V1.getNode())
5080       V1 = SrcVector;
5081     CanFold = SrcVector == V1 &&
5082       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5083   }
5084
5085   if (!CanFold)
5086     return SDValue();
5087
5088   assert(V1.getNode() && "Expected at least two non-zero elements!");
5089   if (V1.getSimpleValueType() != MVT::v4f32)
5090     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5091   if (V2.getSimpleValueType() != MVT::v4f32)
5092     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5093
5094   // Ok, we can emit an INSERTPS instruction.
5095   unsigned ZMask = Zeroable.to_ulong();
5096
5097   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5098   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5099   SDLoc DL(Op);
5100   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5101                                DAG.getIntPtrConstant(InsertPSMask, DL));
5102   return DAG.getBitcast(VT, Result);
5103 }
5104
5105 /// Return a vector logical shift node.
5106 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5107                          unsigned NumBits, SelectionDAG &DAG,
5108                          const TargetLowering &TLI, SDLoc dl) {
5109   assert(VT.is128BitVector() && "Unknown type for VShift");
5110   MVT ShVT = MVT::v2i64;
5111   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5112   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5113   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5114   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5115   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5116   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5117 }
5118
5119 static SDValue
5120 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5121
5122   // Check if the scalar load can be widened into a vector load. And if
5123   // the address is "base + cst" see if the cst can be "absorbed" into
5124   // the shuffle mask.
5125   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5126     SDValue Ptr = LD->getBasePtr();
5127     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5128       return SDValue();
5129     EVT PVT = LD->getValueType(0);
5130     if (PVT != MVT::i32 && PVT != MVT::f32)
5131       return SDValue();
5132
5133     int FI = -1;
5134     int64_t Offset = 0;
5135     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5136       FI = FINode->getIndex();
5137       Offset = 0;
5138     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5139                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5140       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5141       Offset = Ptr.getConstantOperandVal(1);
5142       Ptr = Ptr.getOperand(0);
5143     } else {
5144       return SDValue();
5145     }
5146
5147     // FIXME: 256-bit vector instructions don't require a strict alignment,
5148     // improve this code to support it better.
5149     unsigned RequiredAlign = VT.getSizeInBits()/8;
5150     SDValue Chain = LD->getChain();
5151     // Make sure the stack object alignment is at least 16 or 32.
5152     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5153     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5154       if (MFI->isFixedObjectIndex(FI)) {
5155         // Can't change the alignment. FIXME: It's possible to compute
5156         // the exact stack offset and reference FI + adjust offset instead.
5157         // If someone *really* cares about this. That's the way to implement it.
5158         return SDValue();
5159       } else {
5160         MFI->setObjectAlignment(FI, RequiredAlign);
5161       }
5162     }
5163
5164     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5165     // Ptr + (Offset & ~15).
5166     if (Offset < 0)
5167       return SDValue();
5168     if ((Offset % RequiredAlign) & 3)
5169       return SDValue();
5170     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5171     if (StartOffset) {
5172       SDLoc DL(Ptr);
5173       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5174                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5175     }
5176
5177     int EltNo = (Offset - StartOffset) >> 2;
5178     unsigned NumElems = VT.getVectorNumElements();
5179
5180     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5181     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5182                              LD->getPointerInfo().getWithOffset(StartOffset),
5183                              false, false, false, 0);
5184
5185     SmallVector<int, 8> Mask(NumElems, EltNo);
5186
5187     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5188   }
5189
5190   return SDValue();
5191 }
5192
5193 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5194 /// elements can be replaced by a single large load which has the same value as
5195 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5196 ///
5197 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5198 ///
5199 /// FIXME: we'd also like to handle the case where the last elements are zero
5200 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5201 /// There's even a handy isZeroNode for that purpose.
5202 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5203                                         SDLoc &DL, SelectionDAG &DAG,
5204                                         bool isAfterLegalize) {
5205   unsigned NumElems = Elts.size();
5206
5207   LoadSDNode *LDBase = nullptr;
5208   unsigned LastLoadedElt = -1U;
5209
5210   // For each element in the initializer, see if we've found a load or an undef.
5211   // If we don't find an initial load element, or later load elements are
5212   // non-consecutive, bail out.
5213   for (unsigned i = 0; i < NumElems; ++i) {
5214     SDValue Elt = Elts[i];
5215     // Look through a bitcast.
5216     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5217       Elt = Elt.getOperand(0);
5218     if (!Elt.getNode() ||
5219         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5220       return SDValue();
5221     if (!LDBase) {
5222       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5223         return SDValue();
5224       LDBase = cast<LoadSDNode>(Elt.getNode());
5225       LastLoadedElt = i;
5226       continue;
5227     }
5228     if (Elt.getOpcode() == ISD::UNDEF)
5229       continue;
5230
5231     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5232     EVT LdVT = Elt.getValueType();
5233     // Each loaded element must be the correct fractional portion of the
5234     // requested vector load.
5235     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5236       return SDValue();
5237     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5238       return SDValue();
5239     LastLoadedElt = i;
5240   }
5241
5242   // If we have found an entire vector of loads and undefs, then return a large
5243   // load of the entire vector width starting at the base pointer.  If we found
5244   // consecutive loads for the low half, generate a vzext_load node.
5245   if (LastLoadedElt == NumElems - 1) {
5246     assert(LDBase && "Did not find base load for merging consecutive loads");
5247     EVT EltVT = LDBase->getValueType(0);
5248     // Ensure that the input vector size for the merged loads matches the
5249     // cumulative size of the input elements.
5250     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5251       return SDValue();
5252
5253     if (isAfterLegalize &&
5254         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5255       return SDValue();
5256
5257     SDValue NewLd = SDValue();
5258
5259     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5260                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5261                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5262                         LDBase->getAlignment());
5263
5264     if (LDBase->hasAnyUseOfValue(1)) {
5265       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5266                                      SDValue(LDBase, 1),
5267                                      SDValue(NewLd.getNode(), 1));
5268       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5269       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5270                              SDValue(NewLd.getNode(), 1));
5271     }
5272
5273     return NewLd;
5274   }
5275
5276   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5277   //of a v4i32 / v4f32. It's probably worth generalizing.
5278   EVT EltVT = VT.getVectorElementType();
5279   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5280       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5281     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5282     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5283     SDValue ResNode =
5284         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5285                                 LDBase->getPointerInfo(),
5286                                 LDBase->getAlignment(),
5287                                 false/*isVolatile*/, true/*ReadMem*/,
5288                                 false/*WriteMem*/);
5289
5290     // Make sure the newly-created LOAD is in the same position as LDBase in
5291     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5292     // update uses of LDBase's output chain to use the TokenFactor.
5293     if (LDBase->hasAnyUseOfValue(1)) {
5294       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5295                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5296       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5297       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5298                              SDValue(ResNode.getNode(), 1));
5299     }
5300
5301     return DAG.getBitcast(VT, ResNode);
5302   }
5303   return SDValue();
5304 }
5305
5306 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5307 /// to generate a splat value for the following cases:
5308 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5309 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5310 /// a scalar load, or a constant.
5311 /// The VBROADCAST node is returned when a pattern is found,
5312 /// or SDValue() otherwise.
5313 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5314                                     SelectionDAG &DAG) {
5315   // VBROADCAST requires AVX.
5316   // TODO: Splats could be generated for non-AVX CPUs using SSE
5317   // instructions, but there's less potential gain for only 128-bit vectors.
5318   if (!Subtarget->hasAVX())
5319     return SDValue();
5320
5321   MVT VT = Op.getSimpleValueType();
5322   SDLoc dl(Op);
5323
5324   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5325          "Unsupported vector type for broadcast.");
5326
5327   SDValue Ld;
5328   bool ConstSplatVal;
5329
5330   switch (Op.getOpcode()) {
5331     default:
5332       // Unknown pattern found.
5333       return SDValue();
5334
5335     case ISD::BUILD_VECTOR: {
5336       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5337       BitVector UndefElements;
5338       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5339
5340       // We need a splat of a single value to use broadcast, and it doesn't
5341       // make any sense if the value is only in one element of the vector.
5342       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5343         return SDValue();
5344
5345       Ld = Splat;
5346       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5347                        Ld.getOpcode() == ISD::ConstantFP);
5348
5349       // Make sure that all of the users of a non-constant load are from the
5350       // BUILD_VECTOR node.
5351       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5352         return SDValue();
5353       break;
5354     }
5355
5356     case ISD::VECTOR_SHUFFLE: {
5357       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5358
5359       // Shuffles must have a splat mask where the first element is
5360       // broadcasted.
5361       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5362         return SDValue();
5363
5364       SDValue Sc = Op.getOperand(0);
5365       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5366           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5367
5368         if (!Subtarget->hasInt256())
5369           return SDValue();
5370
5371         // Use the register form of the broadcast instruction available on AVX2.
5372         if (VT.getSizeInBits() >= 256)
5373           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5374         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5375       }
5376
5377       Ld = Sc.getOperand(0);
5378       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5379                        Ld.getOpcode() == ISD::ConstantFP);
5380
5381       // The scalar_to_vector node and the suspected
5382       // load node must have exactly one user.
5383       // Constants may have multiple users.
5384
5385       // AVX-512 has register version of the broadcast
5386       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5387         Ld.getValueType().getSizeInBits() >= 32;
5388       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5389           !hasRegVer))
5390         return SDValue();
5391       break;
5392     }
5393   }
5394
5395   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5396   bool IsGE256 = (VT.getSizeInBits() >= 256);
5397
5398   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5399   // instruction to save 8 or more bytes of constant pool data.
5400   // TODO: If multiple splats are generated to load the same constant,
5401   // it may be detrimental to overall size. There needs to be a way to detect
5402   // that condition to know if this is truly a size win.
5403   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5404
5405   // Handle broadcasting a single constant scalar from the constant pool
5406   // into a vector.
5407   // On Sandybridge (no AVX2), it is still better to load a constant vector
5408   // from the constant pool and not to broadcast it from a scalar.
5409   // But override that restriction when optimizing for size.
5410   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5411   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5412     EVT CVT = Ld.getValueType();
5413     assert(!CVT.isVector() && "Must not broadcast a vector type");
5414
5415     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5416     // For size optimization, also splat v2f64 and v2i64, and for size opt
5417     // with AVX2, also splat i8 and i16.
5418     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5419     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5420         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5421       const Constant *C = nullptr;
5422       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5423         C = CI->getConstantIntValue();
5424       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5425         C = CF->getConstantFPValue();
5426
5427       assert(C && "Invalid constant type");
5428
5429       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5430       SDValue CP =
5431           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5432       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5433       Ld = DAG.getLoad(
5434           CVT, dl, DAG.getEntryNode(), CP,
5435           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5436           false, false, Alignment);
5437
5438       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5439     }
5440   }
5441
5442   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5443
5444   // Handle AVX2 in-register broadcasts.
5445   if (!IsLoad && Subtarget->hasInt256() &&
5446       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5447     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5448
5449   // The scalar source must be a normal load.
5450   if (!IsLoad)
5451     return SDValue();
5452
5453   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5454       (Subtarget->hasVLX() && ScalarSize == 64))
5455     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5456
5457   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5458   // double since there is no vbroadcastsd xmm
5459   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5460     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5461       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5462   }
5463
5464   // Unsupported broadcast.
5465   return SDValue();
5466 }
5467
5468 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5469 /// underlying vector and index.
5470 ///
5471 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5472 /// index.
5473 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5474                                          SDValue ExtIdx) {
5475   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5476   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5477     return Idx;
5478
5479   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5480   // lowered this:
5481   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5482   // to:
5483   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5484   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5485   //                           undef)
5486   //                       Constant<0>)
5487   // In this case the vector is the extract_subvector expression and the index
5488   // is 2, as specified by the shuffle.
5489   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5490   SDValue ShuffleVec = SVOp->getOperand(0);
5491   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5492   assert(ShuffleVecVT.getVectorElementType() ==
5493          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5494
5495   int ShuffleIdx = SVOp->getMaskElt(Idx);
5496   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5497     ExtractedFromVec = ShuffleVec;
5498     return ShuffleIdx;
5499   }
5500   return Idx;
5501 }
5502
5503 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5504   MVT VT = Op.getSimpleValueType();
5505
5506   // Skip if insert_vec_elt is not supported.
5507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5508   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5509     return SDValue();
5510
5511   SDLoc DL(Op);
5512   unsigned NumElems = Op.getNumOperands();
5513
5514   SDValue VecIn1;
5515   SDValue VecIn2;
5516   SmallVector<unsigned, 4> InsertIndices;
5517   SmallVector<int, 8> Mask(NumElems, -1);
5518
5519   for (unsigned i = 0; i != NumElems; ++i) {
5520     unsigned Opc = Op.getOperand(i).getOpcode();
5521
5522     if (Opc == ISD::UNDEF)
5523       continue;
5524
5525     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5526       // Quit if more than 1 elements need inserting.
5527       if (InsertIndices.size() > 1)
5528         return SDValue();
5529
5530       InsertIndices.push_back(i);
5531       continue;
5532     }
5533
5534     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5535     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5536     // Quit if non-constant index.
5537     if (!isa<ConstantSDNode>(ExtIdx))
5538       return SDValue();
5539     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5540
5541     // Quit if extracted from vector of different type.
5542     if (ExtractedFromVec.getValueType() != VT)
5543       return SDValue();
5544
5545     if (!VecIn1.getNode())
5546       VecIn1 = ExtractedFromVec;
5547     else if (VecIn1 != ExtractedFromVec) {
5548       if (!VecIn2.getNode())
5549         VecIn2 = ExtractedFromVec;
5550       else if (VecIn2 != ExtractedFromVec)
5551         // Quit if more than 2 vectors to shuffle
5552         return SDValue();
5553     }
5554
5555     if (ExtractedFromVec == VecIn1)
5556       Mask[i] = Idx;
5557     else if (ExtractedFromVec == VecIn2)
5558       Mask[i] = Idx + NumElems;
5559   }
5560
5561   if (!VecIn1.getNode())
5562     return SDValue();
5563
5564   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5565   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5566   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5567     unsigned Idx = InsertIndices[i];
5568     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5569                      DAG.getIntPtrConstant(Idx, DL));
5570   }
5571
5572   return NV;
5573 }
5574
5575 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5576   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5577          Op.getScalarValueSizeInBits() == 1 &&
5578          "Can not convert non-constant vector");
5579   uint64_t Immediate = 0;
5580   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5581     SDValue In = Op.getOperand(idx);
5582     if (In.getOpcode() != ISD::UNDEF)
5583       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5584   }
5585   SDLoc dl(Op);
5586   MVT VT =
5587    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5588   return DAG.getConstant(Immediate, dl, VT);
5589 }
5590 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5591 SDValue
5592 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5593
5594   MVT VT = Op.getSimpleValueType();
5595   assert((VT.getVectorElementType() == MVT::i1) &&
5596          "Unexpected type in LowerBUILD_VECTORvXi1!");
5597
5598   SDLoc dl(Op);
5599   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5600     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5601     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5602     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5603   }
5604
5605   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5606     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5607     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5608     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5609   }
5610
5611   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5612     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5613     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5614       return DAG.getBitcast(VT, Imm);
5615     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5616     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5617                         DAG.getIntPtrConstant(0, dl));
5618   }
5619
5620   // Vector has one or more non-const elements
5621   uint64_t Immediate = 0;
5622   SmallVector<unsigned, 16> NonConstIdx;
5623   bool IsSplat = true;
5624   bool HasConstElts = false;
5625   int SplatIdx = -1;
5626   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5627     SDValue In = Op.getOperand(idx);
5628     if (In.getOpcode() == ISD::UNDEF)
5629       continue;
5630     if (!isa<ConstantSDNode>(In))
5631       NonConstIdx.push_back(idx);
5632     else {
5633       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5634       HasConstElts = true;
5635     }
5636     if (SplatIdx == -1)
5637       SplatIdx = idx;
5638     else if (In != Op.getOperand(SplatIdx))
5639       IsSplat = false;
5640   }
5641
5642   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5643   if (IsSplat)
5644     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5645                        DAG.getConstant(1, dl, VT),
5646                        DAG.getConstant(0, dl, VT));
5647
5648   // insert elements one by one
5649   SDValue DstVec;
5650   SDValue Imm;
5651   if (Immediate) {
5652     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5653     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5654   }
5655   else if (HasConstElts)
5656     Imm = DAG.getConstant(0, dl, VT);
5657   else
5658     Imm = DAG.getUNDEF(VT);
5659   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5660     DstVec = DAG.getBitcast(VT, Imm);
5661   else {
5662     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5663     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5664                          DAG.getIntPtrConstant(0, dl));
5665   }
5666
5667   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5668     unsigned InsertIdx = NonConstIdx[i];
5669     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5670                          Op.getOperand(InsertIdx),
5671                          DAG.getIntPtrConstant(InsertIdx, dl));
5672   }
5673   return DstVec;
5674 }
5675
5676 /// \brief Return true if \p N implements a horizontal binop and return the
5677 /// operands for the horizontal binop into V0 and V1.
5678 ///
5679 /// This is a helper function of LowerToHorizontalOp().
5680 /// This function checks that the build_vector \p N in input implements a
5681 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5682 /// operation to match.
5683 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5684 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5685 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5686 /// arithmetic sub.
5687 ///
5688 /// This function only analyzes elements of \p N whose indices are
5689 /// in range [BaseIdx, LastIdx).
5690 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5691                               SelectionDAG &DAG,
5692                               unsigned BaseIdx, unsigned LastIdx,
5693                               SDValue &V0, SDValue &V1) {
5694   EVT VT = N->getValueType(0);
5695
5696   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5697   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5698          "Invalid Vector in input!");
5699
5700   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5701   bool CanFold = true;
5702   unsigned ExpectedVExtractIdx = BaseIdx;
5703   unsigned NumElts = LastIdx - BaseIdx;
5704   V0 = DAG.getUNDEF(VT);
5705   V1 = DAG.getUNDEF(VT);
5706
5707   // Check if N implements a horizontal binop.
5708   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5709     SDValue Op = N->getOperand(i + BaseIdx);
5710
5711     // Skip UNDEFs.
5712     if (Op->getOpcode() == ISD::UNDEF) {
5713       // Update the expected vector extract index.
5714       if (i * 2 == NumElts)
5715         ExpectedVExtractIdx = BaseIdx;
5716       ExpectedVExtractIdx += 2;
5717       continue;
5718     }
5719
5720     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5721
5722     if (!CanFold)
5723       break;
5724
5725     SDValue Op0 = Op.getOperand(0);
5726     SDValue Op1 = Op.getOperand(1);
5727
5728     // Try to match the following pattern:
5729     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5730     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5731         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5732         Op0.getOperand(0) == Op1.getOperand(0) &&
5733         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5734         isa<ConstantSDNode>(Op1.getOperand(1)));
5735     if (!CanFold)
5736       break;
5737
5738     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5739     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5740
5741     if (i * 2 < NumElts) {
5742       if (V0.getOpcode() == ISD::UNDEF) {
5743         V0 = Op0.getOperand(0);
5744         if (V0.getValueType() != VT)
5745           return false;
5746       }
5747     } else {
5748       if (V1.getOpcode() == ISD::UNDEF) {
5749         V1 = Op0.getOperand(0);
5750         if (V1.getValueType() != VT)
5751           return false;
5752       }
5753       if (i * 2 == NumElts)
5754         ExpectedVExtractIdx = BaseIdx;
5755     }
5756
5757     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5758     if (I0 == ExpectedVExtractIdx)
5759       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5760     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5761       // Try to match the following dag sequence:
5762       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5763       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5764     } else
5765       CanFold = false;
5766
5767     ExpectedVExtractIdx += 2;
5768   }
5769
5770   return CanFold;
5771 }
5772
5773 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5774 /// a concat_vector.
5775 ///
5776 /// This is a helper function of LowerToHorizontalOp().
5777 /// This function expects two 256-bit vectors called V0 and V1.
5778 /// At first, each vector is split into two separate 128-bit vectors.
5779 /// Then, the resulting 128-bit vectors are used to implement two
5780 /// horizontal binary operations.
5781 ///
5782 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5783 ///
5784 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5785 /// the two new horizontal binop.
5786 /// When Mode is set, the first horizontal binop dag node would take as input
5787 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5788 /// horizontal binop dag node would take as input the lower 128-bit of V1
5789 /// and the upper 128-bit of V1.
5790 ///   Example:
5791 ///     HADD V0_LO, V0_HI
5792 ///     HADD V1_LO, V1_HI
5793 ///
5794 /// Otherwise, the first horizontal binop dag node takes as input the lower
5795 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5796 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5797 ///   Example:
5798 ///     HADD V0_LO, V1_LO
5799 ///     HADD V0_HI, V1_HI
5800 ///
5801 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5802 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5803 /// the upper 128-bits of the result.
5804 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5805                                      SDLoc DL, SelectionDAG &DAG,
5806                                      unsigned X86Opcode, bool Mode,
5807                                      bool isUndefLO, bool isUndefHI) {
5808   EVT VT = V0.getValueType();
5809   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5810          "Invalid nodes in input!");
5811
5812   unsigned NumElts = VT.getVectorNumElements();
5813   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5814   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5815   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5816   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5817   EVT NewVT = V0_LO.getValueType();
5818
5819   SDValue LO = DAG.getUNDEF(NewVT);
5820   SDValue HI = DAG.getUNDEF(NewVT);
5821
5822   if (Mode) {
5823     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5824     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5825       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5826     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5827       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5828   } else {
5829     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5830     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5831                        V1_LO->getOpcode() != ISD::UNDEF))
5832       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5833
5834     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5835                        V1_HI->getOpcode() != ISD::UNDEF))
5836       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5837   }
5838
5839   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5840 }
5841
5842 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5843 /// node.
5844 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5845                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5846   EVT VT = BV->getValueType(0);
5847   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5848       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5849     return SDValue();
5850
5851   SDLoc DL(BV);
5852   unsigned NumElts = VT.getVectorNumElements();
5853   SDValue InVec0 = DAG.getUNDEF(VT);
5854   SDValue InVec1 = DAG.getUNDEF(VT);
5855
5856   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5857           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5858
5859   // Odd-numbered elements in the input build vector are obtained from
5860   // adding two integer/float elements.
5861   // Even-numbered elements in the input build vector are obtained from
5862   // subtracting two integer/float elements.
5863   unsigned ExpectedOpcode = ISD::FSUB;
5864   unsigned NextExpectedOpcode = ISD::FADD;
5865   bool AddFound = false;
5866   bool SubFound = false;
5867
5868   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5869     SDValue Op = BV->getOperand(i);
5870
5871     // Skip 'undef' values.
5872     unsigned Opcode = Op.getOpcode();
5873     if (Opcode == ISD::UNDEF) {
5874       std::swap(ExpectedOpcode, NextExpectedOpcode);
5875       continue;
5876     }
5877
5878     // Early exit if we found an unexpected opcode.
5879     if (Opcode != ExpectedOpcode)
5880       return SDValue();
5881
5882     SDValue Op0 = Op.getOperand(0);
5883     SDValue Op1 = Op.getOperand(1);
5884
5885     // Try to match the following pattern:
5886     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5887     // Early exit if we cannot match that sequence.
5888     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5889         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5890         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5891         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5892         Op0.getOperand(1) != Op1.getOperand(1))
5893       return SDValue();
5894
5895     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5896     if (I0 != i)
5897       return SDValue();
5898
5899     // We found a valid add/sub node. Update the information accordingly.
5900     if (i & 1)
5901       AddFound = true;
5902     else
5903       SubFound = true;
5904
5905     // Update InVec0 and InVec1.
5906     if (InVec0.getOpcode() == ISD::UNDEF) {
5907       InVec0 = Op0.getOperand(0);
5908       if (InVec0.getValueType() != VT)
5909         return SDValue();
5910     }
5911     if (InVec1.getOpcode() == ISD::UNDEF) {
5912       InVec1 = Op1.getOperand(0);
5913       if (InVec1.getValueType() != VT)
5914         return SDValue();
5915     }
5916
5917     // Make sure that operands in input to each add/sub node always
5918     // come from a same pair of vectors.
5919     if (InVec0 != Op0.getOperand(0)) {
5920       if (ExpectedOpcode == ISD::FSUB)
5921         return SDValue();
5922
5923       // FADD is commutable. Try to commute the operands
5924       // and then test again.
5925       std::swap(Op0, Op1);
5926       if (InVec0 != Op0.getOperand(0))
5927         return SDValue();
5928     }
5929
5930     if (InVec1 != Op1.getOperand(0))
5931       return SDValue();
5932
5933     // Update the pair of expected opcodes.
5934     std::swap(ExpectedOpcode, NextExpectedOpcode);
5935   }
5936
5937   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5938   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5939       InVec1.getOpcode() != ISD::UNDEF)
5940     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5941
5942   return SDValue();
5943 }
5944
5945 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5946 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5947                                    const X86Subtarget *Subtarget,
5948                                    SelectionDAG &DAG) {
5949   EVT VT = BV->getValueType(0);
5950   unsigned NumElts = VT.getVectorNumElements();
5951   unsigned NumUndefsLO = 0;
5952   unsigned NumUndefsHI = 0;
5953   unsigned Half = NumElts/2;
5954
5955   // Count the number of UNDEF operands in the build_vector in input.
5956   for (unsigned i = 0, e = Half; i != e; ++i)
5957     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5958       NumUndefsLO++;
5959
5960   for (unsigned i = Half, e = NumElts; i != e; ++i)
5961     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5962       NumUndefsHI++;
5963
5964   // Early exit if this is either a build_vector of all UNDEFs or all the
5965   // operands but one are UNDEF.
5966   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5967     return SDValue();
5968
5969   SDLoc DL(BV);
5970   SDValue InVec0, InVec1;
5971   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5972     // Try to match an SSE3 float HADD/HSUB.
5973     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5974       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5975
5976     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5977       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5978   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5979     // Try to match an SSSE3 integer HADD/HSUB.
5980     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5981       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5982
5983     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5984       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5985   }
5986
5987   if (!Subtarget->hasAVX())
5988     return SDValue();
5989
5990   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5991     // Try to match an AVX horizontal add/sub of packed single/double
5992     // precision floating point values from 256-bit vectors.
5993     SDValue InVec2, InVec3;
5994     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5995         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5996         ((InVec0.getOpcode() == ISD::UNDEF ||
5997           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5998         ((InVec1.getOpcode() == ISD::UNDEF ||
5999           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6000       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6001
6002     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6003         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6004         ((InVec0.getOpcode() == ISD::UNDEF ||
6005           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6006         ((InVec1.getOpcode() == ISD::UNDEF ||
6007           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6008       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6009   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6010     // Try to match an AVX2 horizontal add/sub of signed integers.
6011     SDValue InVec2, InVec3;
6012     unsigned X86Opcode;
6013     bool CanFold = true;
6014
6015     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6016         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6017         ((InVec0.getOpcode() == ISD::UNDEF ||
6018           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6019         ((InVec1.getOpcode() == ISD::UNDEF ||
6020           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6021       X86Opcode = X86ISD::HADD;
6022     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6023         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6024         ((InVec0.getOpcode() == ISD::UNDEF ||
6025           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6026         ((InVec1.getOpcode() == ISD::UNDEF ||
6027           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6028       X86Opcode = X86ISD::HSUB;
6029     else
6030       CanFold = false;
6031
6032     if (CanFold) {
6033       // Fold this build_vector into a single horizontal add/sub.
6034       // Do this only if the target has AVX2.
6035       if (Subtarget->hasAVX2())
6036         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6037
6038       // Do not try to expand this build_vector into a pair of horizontal
6039       // add/sub if we can emit a pair of scalar add/sub.
6040       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6041         return SDValue();
6042
6043       // Convert this build_vector into a pair of horizontal binop followed by
6044       // a concat vector.
6045       bool isUndefLO = NumUndefsLO == Half;
6046       bool isUndefHI = NumUndefsHI == Half;
6047       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6048                                    isUndefLO, isUndefHI);
6049     }
6050   }
6051
6052   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6053        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6054     unsigned X86Opcode;
6055     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6056       X86Opcode = X86ISD::HADD;
6057     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6058       X86Opcode = X86ISD::HSUB;
6059     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6060       X86Opcode = X86ISD::FHADD;
6061     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6062       X86Opcode = X86ISD::FHSUB;
6063     else
6064       return SDValue();
6065
6066     // Don't try to expand this build_vector into a pair of horizontal add/sub
6067     // if we can simply emit a pair of scalar add/sub.
6068     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6069       return SDValue();
6070
6071     // Convert this build_vector into two horizontal add/sub followed by
6072     // a concat vector.
6073     bool isUndefLO = NumUndefsLO == Half;
6074     bool isUndefHI = NumUndefsHI == Half;
6075     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6076                                  isUndefLO, isUndefHI);
6077   }
6078
6079   return SDValue();
6080 }
6081
6082 SDValue
6083 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6084   SDLoc dl(Op);
6085
6086   MVT VT = Op.getSimpleValueType();
6087   MVT ExtVT = VT.getVectorElementType();
6088   unsigned NumElems = Op.getNumOperands();
6089
6090   // Generate vectors for predicate vectors.
6091   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6092     return LowerBUILD_VECTORvXi1(Op, DAG);
6093
6094   // Vectors containing all zeros can be matched by pxor and xorps later
6095   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6096     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6097     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6098     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6099       return Op;
6100
6101     return getZeroVector(VT, Subtarget, DAG, dl);
6102   }
6103
6104   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6105   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6106   // vpcmpeqd on 256-bit vectors.
6107   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6108     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6109       return Op;
6110
6111     if (!VT.is512BitVector())
6112       return getOnesVector(VT, Subtarget, DAG, dl);
6113   }
6114
6115   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6116   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6117     return AddSub;
6118   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6119     return HorizontalOp;
6120   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6121     return Broadcast;
6122
6123   unsigned EVTBits = ExtVT.getSizeInBits();
6124
6125   unsigned NumZero  = 0;
6126   unsigned NumNonZero = 0;
6127   unsigned NonZeros = 0;
6128   bool IsAllConstants = true;
6129   SmallSet<SDValue, 8> Values;
6130   for (unsigned i = 0; i < NumElems; ++i) {
6131     SDValue Elt = Op.getOperand(i);
6132     if (Elt.getOpcode() == ISD::UNDEF)
6133       continue;
6134     Values.insert(Elt);
6135     if (Elt.getOpcode() != ISD::Constant &&
6136         Elt.getOpcode() != ISD::ConstantFP)
6137       IsAllConstants = false;
6138     if (X86::isZeroNode(Elt))
6139       NumZero++;
6140     else {
6141       NonZeros |= (1 << i);
6142       NumNonZero++;
6143     }
6144   }
6145
6146   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6147   if (NumNonZero == 0)
6148     return DAG.getUNDEF(VT);
6149
6150   // Special case for single non-zero, non-undef, element.
6151   if (NumNonZero == 1) {
6152     unsigned Idx = countTrailingZeros(NonZeros);
6153     SDValue Item = Op.getOperand(Idx);
6154
6155     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6156     // the value are obviously zero, truncate the value to i32 and do the
6157     // insertion that way.  Only do this if the value is non-constant or if the
6158     // value is a constant being inserted into element 0.  It is cheaper to do
6159     // a constant pool load than it is to do a movd + shuffle.
6160     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6161         (!IsAllConstants || Idx == 0)) {
6162       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6163         // Handle SSE only.
6164         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6165         EVT VecVT = MVT::v4i32;
6166
6167         // Truncate the value (which may itself be a constant) to i32, and
6168         // convert it to a vector with movd (S2V+shuffle to zero extend).
6169         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6170         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6171         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6172                                       Item, Idx * 2, true, Subtarget, DAG));
6173       }
6174     }
6175
6176     // If we have a constant or non-constant insertion into the low element of
6177     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6178     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6179     // depending on what the source datatype is.
6180     if (Idx == 0) {
6181       if (NumZero == 0)
6182         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6183
6184       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6185           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6186         if (VT.is512BitVector()) {
6187           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6188           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6189                              Item, DAG.getIntPtrConstant(0, dl));
6190         }
6191         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6192                "Expected an SSE value type!");
6193         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6194         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6195         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6196       }
6197
6198       // We can't directly insert an i8 or i16 into a vector, so zero extend
6199       // it to i32 first.
6200       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6201         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6202         if (VT.is256BitVector()) {
6203           if (Subtarget->hasAVX()) {
6204             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6205             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6206           } else {
6207             // Without AVX, we need to extend to a 128-bit vector and then
6208             // insert into the 256-bit vector.
6209             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6210             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6211             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6212           }
6213         } else {
6214           assert(VT.is128BitVector() && "Expected an SSE value type!");
6215           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6216           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6217         }
6218         return DAG.getBitcast(VT, Item);
6219       }
6220     }
6221
6222     // Is it a vector logical left shift?
6223     if (NumElems == 2 && Idx == 1 &&
6224         X86::isZeroNode(Op.getOperand(0)) &&
6225         !X86::isZeroNode(Op.getOperand(1))) {
6226       unsigned NumBits = VT.getSizeInBits();
6227       return getVShift(true, VT,
6228                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6229                                    VT, Op.getOperand(1)),
6230                        NumBits/2, DAG, *this, dl);
6231     }
6232
6233     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6234       return SDValue();
6235
6236     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6237     // is a non-constant being inserted into an element other than the low one,
6238     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6239     // movd/movss) to move this into the low element, then shuffle it into
6240     // place.
6241     if (EVTBits == 32) {
6242       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6243       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6244     }
6245   }
6246
6247   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6248   if (Values.size() == 1) {
6249     if (EVTBits == 32) {
6250       // Instead of a shuffle like this:
6251       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6252       // Check if it's possible to issue this instead.
6253       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6254       unsigned Idx = countTrailingZeros(NonZeros);
6255       SDValue Item = Op.getOperand(Idx);
6256       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6257         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6258     }
6259     return SDValue();
6260   }
6261
6262   // A vector full of immediates; various special cases are already
6263   // handled, so this is best done with a single constant-pool load.
6264   if (IsAllConstants)
6265     return SDValue();
6266
6267   // For AVX-length vectors, see if we can use a vector load to get all of the
6268   // elements, otherwise build the individual 128-bit pieces and use
6269   // shuffles to put them in place.
6270   if (VT.is256BitVector() || VT.is512BitVector()) {
6271     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6272
6273     // Check for a build vector of consecutive loads.
6274     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6275       return LD;
6276
6277     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6278
6279     // Build both the lower and upper subvector.
6280     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6281                                 makeArrayRef(&V[0], NumElems/2));
6282     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6283                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6284
6285     // Recreate the wider vector with the lower and upper part.
6286     if (VT.is256BitVector())
6287       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6288     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6289   }
6290
6291   // Let legalizer expand 2-wide build_vectors.
6292   if (EVTBits == 64) {
6293     if (NumNonZero == 1) {
6294       // One half is zero or undef.
6295       unsigned Idx = countTrailingZeros(NonZeros);
6296       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6297                                  Op.getOperand(Idx));
6298       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6299     }
6300     return SDValue();
6301   }
6302
6303   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6304   if (EVTBits == 8 && NumElems == 16)
6305     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6306                                         Subtarget, *this))
6307       return V;
6308
6309   if (EVTBits == 16 && NumElems == 8)
6310     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6311                                       Subtarget, *this))
6312       return V;
6313
6314   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6315   if (EVTBits == 32 && NumElems == 4)
6316     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6317       return V;
6318
6319   // If element VT is == 32 bits, turn it into a number of shuffles.
6320   SmallVector<SDValue, 8> V(NumElems);
6321   if (NumElems == 4 && NumZero > 0) {
6322     for (unsigned i = 0; i < 4; ++i) {
6323       bool isZero = !(NonZeros & (1 << i));
6324       if (isZero)
6325         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6326       else
6327         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6328     }
6329
6330     for (unsigned i = 0; i < 2; ++i) {
6331       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6332         default: break;
6333         case 0:
6334           V[i] = V[i*2];  // Must be a zero vector.
6335           break;
6336         case 1:
6337           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6338           break;
6339         case 2:
6340           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6341           break;
6342         case 3:
6343           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6344           break;
6345       }
6346     }
6347
6348     bool Reverse1 = (NonZeros & 0x3) == 2;
6349     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6350     int MaskVec[] = {
6351       Reverse1 ? 1 : 0,
6352       Reverse1 ? 0 : 1,
6353       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6354       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6355     };
6356     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6357   }
6358
6359   if (Values.size() > 1 && VT.is128BitVector()) {
6360     // Check for a build vector of consecutive loads.
6361     for (unsigned i = 0; i < NumElems; ++i)
6362       V[i] = Op.getOperand(i);
6363
6364     // Check for elements which are consecutive loads.
6365     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6366       return LD;
6367
6368     // Check for a build vector from mostly shuffle plus few inserting.
6369     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6370       return Sh;
6371
6372     // For SSE 4.1, use insertps to put the high elements into the low element.
6373     if (Subtarget->hasSSE41()) {
6374       SDValue Result;
6375       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6376         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6377       else
6378         Result = DAG.getUNDEF(VT);
6379
6380       for (unsigned i = 1; i < NumElems; ++i) {
6381         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6382         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6383                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6384       }
6385       return Result;
6386     }
6387
6388     // Otherwise, expand into a number of unpckl*, start by extending each of
6389     // our (non-undef) elements to the full vector width with the element in the
6390     // bottom slot of the vector (which generates no code for SSE).
6391     for (unsigned i = 0; i < NumElems; ++i) {
6392       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6393         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6394       else
6395         V[i] = DAG.getUNDEF(VT);
6396     }
6397
6398     // Next, we iteratively mix elements, e.g. for v4f32:
6399     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6400     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6401     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6402     unsigned EltStride = NumElems >> 1;
6403     while (EltStride != 0) {
6404       for (unsigned i = 0; i < EltStride; ++i) {
6405         // If V[i+EltStride] is undef and this is the first round of mixing,
6406         // then it is safe to just drop this shuffle: V[i] is already in the
6407         // right place, the one element (since it's the first round) being
6408         // inserted as undef can be dropped.  This isn't safe for successive
6409         // rounds because they will permute elements within both vectors.
6410         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6411             EltStride == NumElems/2)
6412           continue;
6413
6414         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6415       }
6416       EltStride >>= 1;
6417     }
6418     return V[0];
6419   }
6420   return SDValue();
6421 }
6422
6423 // 256-bit AVX can use the vinsertf128 instruction
6424 // to create 256-bit vectors from two other 128-bit ones.
6425 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6426   SDLoc dl(Op);
6427   MVT ResVT = Op.getSimpleValueType();
6428
6429   assert((ResVT.is256BitVector() ||
6430           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6431
6432   SDValue V1 = Op.getOperand(0);
6433   SDValue V2 = Op.getOperand(1);
6434   unsigned NumElems = ResVT.getVectorNumElements();
6435   if (ResVT.is256BitVector())
6436     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6437
6438   if (Op.getNumOperands() == 4) {
6439     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6440                                 ResVT.getVectorNumElements()/2);
6441     SDValue V3 = Op.getOperand(2);
6442     SDValue V4 = Op.getOperand(3);
6443     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6444       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6445   }
6446   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6447 }
6448
6449 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6450                                        const X86Subtarget *Subtarget,
6451                                        SelectionDAG & DAG) {
6452   SDLoc dl(Op);
6453   MVT ResVT = Op.getSimpleValueType();
6454   unsigned NumOfOperands = Op.getNumOperands();
6455
6456   assert(isPowerOf2_32(NumOfOperands) &&
6457          "Unexpected number of operands in CONCAT_VECTORS");
6458
6459   if (NumOfOperands > 2) {
6460     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6461                                   ResVT.getVectorNumElements()/2);
6462     SmallVector<SDValue, 2> Ops;
6463     for (unsigned i = 0; i < NumOfOperands/2; i++)
6464       Ops.push_back(Op.getOperand(i));
6465     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6466     Ops.clear();
6467     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6468       Ops.push_back(Op.getOperand(i));
6469     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6470     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6471   }
6472
6473   SDValue V1 = Op.getOperand(0);
6474   SDValue V2 = Op.getOperand(1);
6475   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6476   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6477
6478   if (IsZeroV1 && IsZeroV2)
6479     return getZeroVector(ResVT, Subtarget, DAG, dl);
6480
6481   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6482   SDValue Undef = DAG.getUNDEF(ResVT);
6483   unsigned NumElems = ResVT.getVectorNumElements();
6484   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6485
6486   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6487   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6488   if (IsZeroV1)
6489     return V2;
6490
6491   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6492   // Zero the upper bits of V1
6493   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6494   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6495   if (IsZeroV2)
6496     return V1;
6497   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6498 }
6499
6500 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6501                                    const X86Subtarget *Subtarget,
6502                                    SelectionDAG &DAG) {
6503   MVT VT = Op.getSimpleValueType();
6504   if (VT.getVectorElementType() == MVT::i1)
6505     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6506
6507   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6508          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6509           Op.getNumOperands() == 4)));
6510
6511   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6512   // from two other 128-bit ones.
6513
6514   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6515   return LowerAVXCONCAT_VECTORS(Op, DAG);
6516 }
6517
6518 //===----------------------------------------------------------------------===//
6519 // Vector shuffle lowering
6520 //
6521 // This is an experimental code path for lowering vector shuffles on x86. It is
6522 // designed to handle arbitrary vector shuffles and blends, gracefully
6523 // degrading performance as necessary. It works hard to recognize idiomatic
6524 // shuffles and lower them to optimal instruction patterns without leaving
6525 // a framework that allows reasonably efficient handling of all vector shuffle
6526 // patterns.
6527 //===----------------------------------------------------------------------===//
6528
6529 /// \brief Tiny helper function to identify a no-op mask.
6530 ///
6531 /// This is a somewhat boring predicate function. It checks whether the mask
6532 /// array input, which is assumed to be a single-input shuffle mask of the kind
6533 /// used by the X86 shuffle instructions (not a fully general
6534 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6535 /// in-place shuffle are 'no-op's.
6536 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6537   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6538     if (Mask[i] != -1 && Mask[i] != i)
6539       return false;
6540   return true;
6541 }
6542
6543 /// \brief Helper function to classify a mask as a single-input mask.
6544 ///
6545 /// This isn't a generic single-input test because in the vector shuffle
6546 /// lowering we canonicalize single inputs to be the first input operand. This
6547 /// means we can more quickly test for a single input by only checking whether
6548 /// an input from the second operand exists. We also assume that the size of
6549 /// mask corresponds to the size of the input vectors which isn't true in the
6550 /// fully general case.
6551 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6552   for (int M : Mask)
6553     if (M >= (int)Mask.size())
6554       return false;
6555   return true;
6556 }
6557
6558 /// \brief Test whether there are elements crossing 128-bit lanes in this
6559 /// shuffle mask.
6560 ///
6561 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6562 /// and we routinely test for these.
6563 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6564   int LaneSize = 128 / VT.getScalarSizeInBits();
6565   int Size = Mask.size();
6566   for (int i = 0; i < Size; ++i)
6567     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6568       return true;
6569   return false;
6570 }
6571
6572 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6573 ///
6574 /// This checks a shuffle mask to see if it is performing the same
6575 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6576 /// that it is also not lane-crossing. It may however involve a blend from the
6577 /// same lane of a second vector.
6578 ///
6579 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6580 /// non-trivial to compute in the face of undef lanes. The representation is
6581 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6582 /// entries from both V1 and V2 inputs to the wider mask.
6583 static bool
6584 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6585                                 SmallVectorImpl<int> &RepeatedMask) {
6586   int LaneSize = 128 / VT.getScalarSizeInBits();
6587   RepeatedMask.resize(LaneSize, -1);
6588   int Size = Mask.size();
6589   for (int i = 0; i < Size; ++i) {
6590     if (Mask[i] < 0)
6591       continue;
6592     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6593       // This entry crosses lanes, so there is no way to model this shuffle.
6594       return false;
6595
6596     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6597     if (RepeatedMask[i % LaneSize] == -1)
6598       // This is the first non-undef entry in this slot of a 128-bit lane.
6599       RepeatedMask[i % LaneSize] =
6600           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6601     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6602       // Found a mismatch with the repeated mask.
6603       return false;
6604   }
6605   return true;
6606 }
6607
6608 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6609 /// arguments.
6610 ///
6611 /// This is a fast way to test a shuffle mask against a fixed pattern:
6612 ///
6613 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6614 ///
6615 /// It returns true if the mask is exactly as wide as the argument list, and
6616 /// each element of the mask is either -1 (signifying undef) or the value given
6617 /// in the argument.
6618 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6619                                 ArrayRef<int> ExpectedMask) {
6620   if (Mask.size() != ExpectedMask.size())
6621     return false;
6622
6623   int Size = Mask.size();
6624
6625   // If the values are build vectors, we can look through them to find
6626   // equivalent inputs that make the shuffles equivalent.
6627   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6628   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6629
6630   for (int i = 0; i < Size; ++i)
6631     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6632       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6633       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6634       if (!MaskBV || !ExpectedBV ||
6635           MaskBV->getOperand(Mask[i] % Size) !=
6636               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6637         return false;
6638     }
6639
6640   return true;
6641 }
6642
6643 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6644 ///
6645 /// This helper function produces an 8-bit shuffle immediate corresponding to
6646 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6647 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6648 /// example.
6649 ///
6650 /// NB: We rely heavily on "undef" masks preserving the input lane.
6651 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6652                                           SelectionDAG &DAG) {
6653   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6654   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6655   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6656   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6657   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6658
6659   unsigned Imm = 0;
6660   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6661   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6662   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6663   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6664   return DAG.getConstant(Imm, DL, MVT::i8);
6665 }
6666
6667 /// \brief Compute whether each element of a shuffle is zeroable.
6668 ///
6669 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6670 /// Either it is an undef element in the shuffle mask, the element of the input
6671 /// referenced is undef, or the element of the input referenced is known to be
6672 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6673 /// as many lanes with this technique as possible to simplify the remaining
6674 /// shuffle.
6675 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6676                                                      SDValue V1, SDValue V2) {
6677   SmallBitVector Zeroable(Mask.size(), false);
6678
6679   while (V1.getOpcode() == ISD::BITCAST)
6680     V1 = V1->getOperand(0);
6681   while (V2.getOpcode() == ISD::BITCAST)
6682     V2 = V2->getOperand(0);
6683
6684   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6685   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6686
6687   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6688     int M = Mask[i];
6689     // Handle the easy cases.
6690     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6691       Zeroable[i] = true;
6692       continue;
6693     }
6694
6695     // If this is an index into a build_vector node (which has the same number
6696     // of elements), dig out the input value and use it.
6697     SDValue V = M < Size ? V1 : V2;
6698     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6699       continue;
6700
6701     SDValue Input = V.getOperand(M % Size);
6702     // The UNDEF opcode check really should be dead code here, but not quite
6703     // worth asserting on (it isn't invalid, just unexpected).
6704     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6705       Zeroable[i] = true;
6706   }
6707
6708   return Zeroable;
6709 }
6710
6711 // X86 has dedicated unpack instructions that can handle specific blend
6712 // operations: UNPCKH and UNPCKL.
6713 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6714                                            SDValue V1, SDValue V2,
6715                                            SelectionDAG &DAG) {
6716   int NumElts = VT.getVectorNumElements();
6717   bool Unpckl = true;
6718   bool Unpckh = true;
6719   bool UnpcklSwapped = true;
6720   bool UnpckhSwapped = true;
6721   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6722
6723   for (int i = 0; i < NumElts; ++i) {
6724     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6725
6726     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6727     int HiPos = LoPos + NumEltsInLane / 2;
6728     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6729     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6730
6731     if (Mask[i] == -1)
6732       continue;
6733     if (Mask[i] != LoPos)
6734       Unpckl = false;
6735     if (Mask[i] != HiPos)
6736       Unpckh = false;
6737     if (Mask[i] != LoPosSwapped)
6738       UnpcklSwapped = false;
6739     if (Mask[i] != HiPosSwapped)
6740       UnpckhSwapped = false;
6741     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6742       return SDValue();
6743   }
6744   if (Unpckl)
6745     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6746   if (Unpckh)
6747     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6748   if (UnpcklSwapped)
6749     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6750   if (UnpckhSwapped)
6751     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6752
6753   llvm_unreachable("Unexpected result of UNPCK mask analysis");
6754   return SDValue();
6755 }
6756
6757 /// \brief Try to emit a bitmask instruction for a shuffle.
6758 ///
6759 /// This handles cases where we can model a blend exactly as a bitmask due to
6760 /// one of the inputs being zeroable.
6761 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6762                                            SDValue V2, ArrayRef<int> Mask,
6763                                            SelectionDAG &DAG) {
6764   MVT EltVT = VT.getScalarType();
6765   int NumEltBits = EltVT.getSizeInBits();
6766   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6767   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6768   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6769                                     IntEltVT);
6770   if (EltVT.isFloatingPoint()) {
6771     Zero = DAG.getBitcast(EltVT, Zero);
6772     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6773   }
6774   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6775   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6776   SDValue V;
6777   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6778     if (Zeroable[i])
6779       continue;
6780     if (Mask[i] % Size != i)
6781       return SDValue(); // Not a blend.
6782     if (!V)
6783       V = Mask[i] < Size ? V1 : V2;
6784     else if (V != (Mask[i] < Size ? V1 : V2))
6785       return SDValue(); // Can only let one input through the mask.
6786
6787     VMaskOps[i] = AllOnes;
6788   }
6789   if (!V)
6790     return SDValue(); // No non-zeroable elements!
6791
6792   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6793   V = DAG.getNode(VT.isFloatingPoint()
6794                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6795                   DL, VT, V, VMask);
6796   return V;
6797 }
6798
6799 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6800 ///
6801 /// This is used as a fallback approach when first class blend instructions are
6802 /// unavailable. Currently it is only suitable for integer vectors, but could
6803 /// be generalized for floating point vectors if desirable.
6804 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6805                                             SDValue V2, ArrayRef<int> Mask,
6806                                             SelectionDAG &DAG) {
6807   assert(VT.isInteger() && "Only supports integer vector types!");
6808   MVT EltVT = VT.getScalarType();
6809   int NumEltBits = EltVT.getSizeInBits();
6810   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6811   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6812                                     EltVT);
6813   SmallVector<SDValue, 16> MaskOps;
6814   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6815     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6816       return SDValue(); // Shuffled input!
6817     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6818   }
6819
6820   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6821   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6822   // We have to cast V2 around.
6823   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6824   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6825                                       DAG.getBitcast(MaskVT, V1Mask),
6826                                       DAG.getBitcast(MaskVT, V2)));
6827   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6828 }
6829
6830 /// \brief Try to emit a blend instruction for a shuffle.
6831 ///
6832 /// This doesn't do any checks for the availability of instructions for blending
6833 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6834 /// be matched in the backend with the type given. What it does check for is
6835 /// that the shuffle mask is in fact a blend.
6836 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6837                                          SDValue V2, ArrayRef<int> Mask,
6838                                          const X86Subtarget *Subtarget,
6839                                          SelectionDAG &DAG) {
6840   unsigned BlendMask = 0;
6841   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6842     if (Mask[i] >= Size) {
6843       if (Mask[i] != i + Size)
6844         return SDValue(); // Shuffled V2 input!
6845       BlendMask |= 1u << i;
6846       continue;
6847     }
6848     if (Mask[i] >= 0 && Mask[i] != i)
6849       return SDValue(); // Shuffled V1 input!
6850   }
6851   switch (VT.SimpleTy) {
6852   case MVT::v2f64:
6853   case MVT::v4f32:
6854   case MVT::v4f64:
6855   case MVT::v8f32:
6856     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6857                        DAG.getConstant(BlendMask, DL, MVT::i8));
6858
6859   case MVT::v4i64:
6860   case MVT::v8i32:
6861     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6862     // FALLTHROUGH
6863   case MVT::v2i64:
6864   case MVT::v4i32:
6865     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6866     // that instruction.
6867     if (Subtarget->hasAVX2()) {
6868       // Scale the blend by the number of 32-bit dwords per element.
6869       int Scale =  VT.getScalarSizeInBits() / 32;
6870       BlendMask = 0;
6871       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6872         if (Mask[i] >= Size)
6873           for (int j = 0; j < Scale; ++j)
6874             BlendMask |= 1u << (i * Scale + j);
6875
6876       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6877       V1 = DAG.getBitcast(BlendVT, V1);
6878       V2 = DAG.getBitcast(BlendVT, V2);
6879       return DAG.getBitcast(
6880           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6881                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6882     }
6883     // FALLTHROUGH
6884   case MVT::v8i16: {
6885     // For integer shuffles we need to expand the mask and cast the inputs to
6886     // v8i16s prior to blending.
6887     int Scale = 8 / VT.getVectorNumElements();
6888     BlendMask = 0;
6889     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6890       if (Mask[i] >= Size)
6891         for (int j = 0; j < Scale; ++j)
6892           BlendMask |= 1u << (i * Scale + j);
6893
6894     V1 = DAG.getBitcast(MVT::v8i16, V1);
6895     V2 = DAG.getBitcast(MVT::v8i16, V2);
6896     return DAG.getBitcast(VT,
6897                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6898                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6899   }
6900
6901   case MVT::v16i16: {
6902     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6903     SmallVector<int, 8> RepeatedMask;
6904     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6905       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6906       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6907       BlendMask = 0;
6908       for (int i = 0; i < 8; ++i)
6909         if (RepeatedMask[i] >= 16)
6910           BlendMask |= 1u << i;
6911       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6912                          DAG.getConstant(BlendMask, DL, MVT::i8));
6913     }
6914   }
6915     // FALLTHROUGH
6916   case MVT::v16i8:
6917   case MVT::v32i8: {
6918     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6919            "256-bit byte-blends require AVX2 support!");
6920
6921     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6922     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6923       return Masked;
6924
6925     // Scale the blend by the number of bytes per element.
6926     int Scale = VT.getScalarSizeInBits() / 8;
6927
6928     // This form of blend is always done on bytes. Compute the byte vector
6929     // type.
6930     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6931
6932     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6933     // mix of LLVM's code generator and the x86 backend. We tell the code
6934     // generator that boolean values in the elements of an x86 vector register
6935     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6936     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6937     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6938     // of the element (the remaining are ignored) and 0 in that high bit would
6939     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6940     // the LLVM model for boolean values in vector elements gets the relevant
6941     // bit set, it is set backwards and over constrained relative to x86's
6942     // actual model.
6943     SmallVector<SDValue, 32> VSELECTMask;
6944     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6945       for (int j = 0; j < Scale; ++j)
6946         VSELECTMask.push_back(
6947             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6948                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6949                                           MVT::i8));
6950
6951     V1 = DAG.getBitcast(BlendVT, V1);
6952     V2 = DAG.getBitcast(BlendVT, V2);
6953     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6954                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6955                                                       BlendVT, VSELECTMask),
6956                                           V1, V2));
6957   }
6958
6959   default:
6960     llvm_unreachable("Not a supported integer vector type!");
6961   }
6962 }
6963
6964 /// \brief Try to lower as a blend of elements from two inputs followed by
6965 /// a single-input permutation.
6966 ///
6967 /// This matches the pattern where we can blend elements from two inputs and
6968 /// then reduce the shuffle to a single-input permutation.
6969 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6970                                                    SDValue V2,
6971                                                    ArrayRef<int> Mask,
6972                                                    SelectionDAG &DAG) {
6973   // We build up the blend mask while checking whether a blend is a viable way
6974   // to reduce the shuffle.
6975   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6976   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6977
6978   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6979     if (Mask[i] < 0)
6980       continue;
6981
6982     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6983
6984     if (BlendMask[Mask[i] % Size] == -1)
6985       BlendMask[Mask[i] % Size] = Mask[i];
6986     else if (BlendMask[Mask[i] % Size] != Mask[i])
6987       return SDValue(); // Can't blend in the needed input!
6988
6989     PermuteMask[i] = Mask[i] % Size;
6990   }
6991
6992   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6993   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6994 }
6995
6996 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6997 /// blends and permutes.
6998 ///
6999 /// This matches the extremely common pattern for handling combined
7000 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7001 /// operations. It will try to pick the best arrangement of shuffles and
7002 /// blends.
7003 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7004                                                           SDValue V1,
7005                                                           SDValue V2,
7006                                                           ArrayRef<int> Mask,
7007                                                           SelectionDAG &DAG) {
7008   // Shuffle the input elements into the desired positions in V1 and V2 and
7009   // blend them together.
7010   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7011   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7012   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7013   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7014     if (Mask[i] >= 0 && Mask[i] < Size) {
7015       V1Mask[i] = Mask[i];
7016       BlendMask[i] = i;
7017     } else if (Mask[i] >= Size) {
7018       V2Mask[i] = Mask[i] - Size;
7019       BlendMask[i] = i + Size;
7020     }
7021
7022   // Try to lower with the simpler initial blend strategy unless one of the
7023   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7024   // shuffle may be able to fold with a load or other benefit. However, when
7025   // we'll have to do 2x as many shuffles in order to achieve this, blending
7026   // first is a better strategy.
7027   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7028     if (SDValue BlendPerm =
7029             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7030       return BlendPerm;
7031
7032   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7033   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7034   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7035 }
7036
7037 /// \brief Try to lower a vector shuffle as a byte rotation.
7038 ///
7039 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7040 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7041 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7042 /// try to generically lower a vector shuffle through such an pattern. It
7043 /// does not check for the profitability of lowering either as PALIGNR or
7044 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7045 /// This matches shuffle vectors that look like:
7046 ///
7047 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7048 ///
7049 /// Essentially it concatenates V1 and V2, shifts right by some number of
7050 /// elements, and takes the low elements as the result. Note that while this is
7051 /// specified as a *right shift* because x86 is little-endian, it is a *left
7052 /// rotate* of the vector lanes.
7053 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7054                                               SDValue V2,
7055                                               ArrayRef<int> Mask,
7056                                               const X86Subtarget *Subtarget,
7057                                               SelectionDAG &DAG) {
7058   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7059
7060   int NumElts = Mask.size();
7061   int NumLanes = VT.getSizeInBits() / 128;
7062   int NumLaneElts = NumElts / NumLanes;
7063
7064   // We need to detect various ways of spelling a rotation:
7065   //   [11, 12, 13, 14, 15,  0,  1,  2]
7066   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7067   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7068   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7069   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7070   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7071   int Rotation = 0;
7072   SDValue Lo, Hi;
7073   for (int l = 0; l < NumElts; l += NumLaneElts) {
7074     for (int i = 0; i < NumLaneElts; ++i) {
7075       if (Mask[l + i] == -1)
7076         continue;
7077       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7078
7079       // Get the mod-Size index and lane correct it.
7080       int LaneIdx = (Mask[l + i] % NumElts) - l;
7081       // Make sure it was in this lane.
7082       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7083         return SDValue();
7084
7085       // Determine where a rotated vector would have started.
7086       int StartIdx = i - LaneIdx;
7087       if (StartIdx == 0)
7088         // The identity rotation isn't interesting, stop.
7089         return SDValue();
7090
7091       // If we found the tail of a vector the rotation must be the missing
7092       // front. If we found the head of a vector, it must be how much of the
7093       // head.
7094       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7095
7096       if (Rotation == 0)
7097         Rotation = CandidateRotation;
7098       else if (Rotation != CandidateRotation)
7099         // The rotations don't match, so we can't match this mask.
7100         return SDValue();
7101
7102       // Compute which value this mask is pointing at.
7103       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7104
7105       // Compute which of the two target values this index should be assigned
7106       // to. This reflects whether the high elements are remaining or the low
7107       // elements are remaining.
7108       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7109
7110       // Either set up this value if we've not encountered it before, or check
7111       // that it remains consistent.
7112       if (!TargetV)
7113         TargetV = MaskV;
7114       else if (TargetV != MaskV)
7115         // This may be a rotation, but it pulls from the inputs in some
7116         // unsupported interleaving.
7117         return SDValue();
7118     }
7119   }
7120
7121   // Check that we successfully analyzed the mask, and normalize the results.
7122   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7123   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7124   if (!Lo)
7125     Lo = Hi;
7126   else if (!Hi)
7127     Hi = Lo;
7128
7129   // The actual rotate instruction rotates bytes, so we need to scale the
7130   // rotation based on how many bytes are in the vector lane.
7131   int Scale = 16 / NumLaneElts;
7132
7133   // SSSE3 targets can use the palignr instruction.
7134   if (Subtarget->hasSSSE3()) {
7135     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7136     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7137     Lo = DAG.getBitcast(AlignVT, Lo);
7138     Hi = DAG.getBitcast(AlignVT, Hi);
7139
7140     return DAG.getBitcast(
7141         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7142                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7143   }
7144
7145   assert(VT.getSizeInBits() == 128 &&
7146          "Rotate-based lowering only supports 128-bit lowering!");
7147   assert(Mask.size() <= 16 &&
7148          "Can shuffle at most 16 bytes in a 128-bit vector!");
7149
7150   // Default SSE2 implementation
7151   int LoByteShift = 16 - Rotation * Scale;
7152   int HiByteShift = Rotation * Scale;
7153
7154   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7155   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7156   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7157
7158   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7159                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7160   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7161                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7162   return DAG.getBitcast(VT,
7163                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7164 }
7165
7166 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7167 ///
7168 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7169 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7170 /// matches elements from one of the input vectors shuffled to the left or
7171 /// right with zeroable elements 'shifted in'. It handles both the strictly
7172 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7173 /// quad word lane.
7174 ///
7175 /// PSHL : (little-endian) left bit shift.
7176 /// [ zz, 0, zz,  2 ]
7177 /// [ -1, 4, zz, -1 ]
7178 /// PSRL : (little-endian) right bit shift.
7179 /// [  1, zz,  3, zz]
7180 /// [ -1, -1,  7, zz]
7181 /// PSLLDQ : (little-endian) left byte shift
7182 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7183 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7184 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7185 /// PSRLDQ : (little-endian) right byte shift
7186 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7187 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7188 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7189 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7190                                          SDValue V2, ArrayRef<int> Mask,
7191                                          SelectionDAG &DAG) {
7192   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7193
7194   int Size = Mask.size();
7195   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7196
7197   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7198     for (int i = 0; i < Size; i += Scale)
7199       for (int j = 0; j < Shift; ++j)
7200         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7201           return false;
7202
7203     return true;
7204   };
7205
7206   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7207     for (int i = 0; i != Size; i += Scale) {
7208       unsigned Pos = Left ? i + Shift : i;
7209       unsigned Low = Left ? i : i + Shift;
7210       unsigned Len = Scale - Shift;
7211       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7212                                       Low + (V == V1 ? 0 : Size)))
7213         return SDValue();
7214     }
7215
7216     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7217     bool ByteShift = ShiftEltBits > 64;
7218     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7219                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7220     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7221
7222     // Normalize the scale for byte shifts to still produce an i64 element
7223     // type.
7224     Scale = ByteShift ? Scale / 2 : Scale;
7225
7226     // We need to round trip through the appropriate type for the shift.
7227     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7228     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7229     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7230            "Illegal integer vector type");
7231     V = DAG.getBitcast(ShiftVT, V);
7232
7233     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7234                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7235     return DAG.getBitcast(VT, V);
7236   };
7237
7238   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7239   // keep doubling the size of the integer elements up to that. We can
7240   // then shift the elements of the integer vector by whole multiples of
7241   // their width within the elements of the larger integer vector. Test each
7242   // multiple to see if we can find a match with the moved element indices
7243   // and that the shifted in elements are all zeroable.
7244   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7245     for (int Shift = 1; Shift != Scale; ++Shift)
7246       for (bool Left : {true, false})
7247         if (CheckZeros(Shift, Scale, Left))
7248           for (SDValue V : {V1, V2})
7249             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7250               return Match;
7251
7252   // no match
7253   return SDValue();
7254 }
7255
7256 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7257 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7258                                            SDValue V2, ArrayRef<int> Mask,
7259                                            SelectionDAG &DAG) {
7260   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7261   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7262
7263   int Size = Mask.size();
7264   int HalfSize = Size / 2;
7265   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7266
7267   // Upper half must be undefined.
7268   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7269     return SDValue();
7270
7271   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7272   // Remainder of lower half result is zero and upper half is all undef.
7273   auto LowerAsEXTRQ = [&]() {
7274     // Determine the extraction length from the part of the
7275     // lower half that isn't zeroable.
7276     int Len = HalfSize;
7277     for (; Len >= 0; --Len)
7278       if (!Zeroable[Len - 1])
7279         break;
7280     assert(Len > 0 && "Zeroable shuffle mask");
7281
7282     // Attempt to match first Len sequential elements from the lower half.
7283     SDValue Src;
7284     int Idx = -1;
7285     for (int i = 0; i != Len; ++i) {
7286       int M = Mask[i];
7287       if (M < 0)
7288         continue;
7289       SDValue &V = (M < Size ? V1 : V2);
7290       M = M % Size;
7291
7292       // All mask elements must be in the lower half.
7293       if (M > HalfSize)
7294         return SDValue();
7295
7296       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7297         Src = V;
7298         Idx = M - i;
7299         continue;
7300       }
7301       return SDValue();
7302     }
7303
7304     if (Idx < 0)
7305       return SDValue();
7306
7307     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7308     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7309     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7310     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7311                        DAG.getConstant(BitLen, DL, MVT::i8),
7312                        DAG.getConstant(BitIdx, DL, MVT::i8));
7313   };
7314
7315   if (SDValue ExtrQ = LowerAsEXTRQ())
7316     return ExtrQ;
7317
7318   // INSERTQ: Extract lowest Len elements from lower half of second source and
7319   // insert over first source, starting at Idx.
7320   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7321   auto LowerAsInsertQ = [&]() {
7322     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7323       SDValue Base;
7324
7325       // Attempt to match first source from mask before insertion point.
7326       if (isUndefInRange(Mask, 0, Idx)) {
7327         /* EMPTY */
7328       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7329         Base = V1;
7330       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7331         Base = V2;
7332       } else {
7333         continue;
7334       }
7335
7336       // Extend the extraction length looking to match both the insertion of
7337       // the second source and the remaining elements of the first.
7338       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7339         SDValue Insert;
7340         int Len = Hi - Idx;
7341
7342         // Match insertion.
7343         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7344           Insert = V1;
7345         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7346           Insert = V2;
7347         } else {
7348           continue;
7349         }
7350
7351         // Match the remaining elements of the lower half.
7352         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7353           /* EMPTY */
7354         } else if ((!Base || (Base == V1)) &&
7355                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7356           Base = V1;
7357         } else if ((!Base || (Base == V2)) &&
7358                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7359                                               Size + Hi)) {
7360           Base = V2;
7361         } else {
7362           continue;
7363         }
7364
7365         // We may not have a base (first source) - this can safely be undefined.
7366         if (!Base)
7367           Base = DAG.getUNDEF(VT);
7368
7369         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7370         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7371         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7372                            DAG.getConstant(BitLen, DL, MVT::i8),
7373                            DAG.getConstant(BitIdx, DL, MVT::i8));
7374       }
7375     }
7376
7377     return SDValue();
7378   };
7379
7380   if (SDValue InsertQ = LowerAsInsertQ())
7381     return InsertQ;
7382
7383   return SDValue();
7384 }
7385
7386 /// \brief Lower a vector shuffle as a zero or any extension.
7387 ///
7388 /// Given a specific number of elements, element bit width, and extension
7389 /// stride, produce either a zero or any extension based on the available
7390 /// features of the subtarget. The extended elements are consecutive and
7391 /// begin and can start from an offseted element index in the input; to
7392 /// avoid excess shuffling the offset must either being in the bottom lane
7393 /// or at the start of a higher lane. All extended elements must be from
7394 /// the same lane.
7395 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7396     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7397     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7398   assert(Scale > 1 && "Need a scale to extend.");
7399   int EltBits = VT.getScalarSizeInBits();
7400   int NumElements = VT.getVectorNumElements();
7401   int NumEltsPerLane = 128 / EltBits;
7402   int OffsetLane = Offset / NumEltsPerLane;
7403   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7404          "Only 8, 16, and 32 bit elements can be extended.");
7405   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7406   assert(0 <= Offset && "Extension offset must be positive.");
7407   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7408          "Extension offset must be in the first lane or start an upper lane.");
7409
7410   // Check that an index is in same lane as the base offset.
7411   auto SafeOffset = [&](int Idx) {
7412     return OffsetLane == (Idx / NumEltsPerLane);
7413   };
7414
7415   // Shift along an input so that the offset base moves to the first element.
7416   auto ShuffleOffset = [&](SDValue V) {
7417     if (!Offset)
7418       return V;
7419
7420     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7421     for (int i = 0; i * Scale < NumElements; ++i) {
7422       int SrcIdx = i + Offset;
7423       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7424     }
7425     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7426   };
7427
7428   // Found a valid zext mask! Try various lowering strategies based on the
7429   // input type and available ISA extensions.
7430   if (Subtarget->hasSSE41()) {
7431     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7432     // PUNPCK will catch this in a later shuffle match.
7433     if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7434       return SDValue();
7435     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7436                                  NumElements / Scale);
7437     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7438     return DAG.getBitcast(VT, InputV);
7439   }
7440
7441   assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7442
7443   // For any extends we can cheat for larger element sizes and use shuffle
7444   // instructions that can fold with a load and/or copy.
7445   if (AnyExt && EltBits == 32) {
7446     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7447                          -1};
7448     return DAG.getBitcast(
7449         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7450                         DAG.getBitcast(MVT::v4i32, InputV),
7451                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7452   }
7453   if (AnyExt && EltBits == 16 && Scale > 2) {
7454     int PSHUFDMask[4] = {Offset / 2, -1,
7455                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7456     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7457                          DAG.getBitcast(MVT::v4i32, InputV),
7458                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7459     int PSHUFWMask[4] = {1, -1, -1, -1};
7460     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7461     return DAG.getBitcast(
7462         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7463                         DAG.getBitcast(MVT::v8i16, InputV),
7464                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7465   }
7466
7467   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7468   // to 64-bits.
7469   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7470     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7471     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7472
7473     int LoIdx = Offset * EltBits;
7474     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7475                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7476                                          DAG.getConstant(EltBits, DL, MVT::i8),
7477                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7478
7479     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7480         !SafeOffset(Offset + 1))
7481       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7482
7483     int HiIdx = (Offset + 1) * EltBits;
7484     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7485                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7486                                          DAG.getConstant(EltBits, DL, MVT::i8),
7487                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7488     return DAG.getNode(ISD::BITCAST, DL, VT,
7489                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7490   }
7491
7492   // If this would require more than 2 unpack instructions to expand, use
7493   // pshufb when available. We can only use more than 2 unpack instructions
7494   // when zero extending i8 elements which also makes it easier to use pshufb.
7495   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7496     assert(NumElements == 16 && "Unexpected byte vector width!");
7497     SDValue PSHUFBMask[16];
7498     for (int i = 0; i < 16; ++i) {
7499       int Idx = Offset + (i / Scale);
7500       PSHUFBMask[i] = DAG.getConstant(
7501           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7502     }
7503     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7504     return DAG.getBitcast(VT,
7505                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7506                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7507                                                   MVT::v16i8, PSHUFBMask)));
7508   }
7509
7510   // If we are extending from an offset, ensure we start on a boundary that
7511   // we can unpack from.
7512   int AlignToUnpack = Offset % (NumElements / Scale);
7513   if (AlignToUnpack) {
7514     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7515     for (int i = AlignToUnpack; i < NumElements; ++i)
7516       ShMask[i - AlignToUnpack] = i;
7517     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7518     Offset -= AlignToUnpack;
7519   }
7520
7521   // Otherwise emit a sequence of unpacks.
7522   do {
7523     unsigned UnpackLoHi = X86ISD::UNPCKL;
7524     if (Offset >= (NumElements / 2)) {
7525       UnpackLoHi = X86ISD::UNPCKH;
7526       Offset -= (NumElements / 2);
7527     }
7528
7529     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7530     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7531                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7532     InputV = DAG.getBitcast(InputVT, InputV);
7533     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7534     Scale /= 2;
7535     EltBits *= 2;
7536     NumElements /= 2;
7537   } while (Scale > 1);
7538   return DAG.getBitcast(VT, InputV);
7539 }
7540
7541 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7542 ///
7543 /// This routine will try to do everything in its power to cleverly lower
7544 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7545 /// check for the profitability of this lowering,  it tries to aggressively
7546 /// match this pattern. It will use all of the micro-architectural details it
7547 /// can to emit an efficient lowering. It handles both blends with all-zero
7548 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7549 /// masking out later).
7550 ///
7551 /// The reason we have dedicated lowering for zext-style shuffles is that they
7552 /// are both incredibly common and often quite performance sensitive.
7553 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7554     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7555     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7556   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7557
7558   int Bits = VT.getSizeInBits();
7559   int NumLanes = Bits / 128;
7560   int NumElements = VT.getVectorNumElements();
7561   int NumEltsPerLane = NumElements / NumLanes;
7562   assert(VT.getScalarSizeInBits() <= 32 &&
7563          "Exceeds 32-bit integer zero extension limit");
7564   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7565
7566   // Define a helper function to check a particular ext-scale and lower to it if
7567   // valid.
7568   auto Lower = [&](int Scale) -> SDValue {
7569     SDValue InputV;
7570     bool AnyExt = true;
7571     int Offset = 0;
7572     int Matches = 0;
7573     for (int i = 0; i < NumElements; ++i) {
7574       int M = Mask[i];
7575       if (M == -1)
7576         continue; // Valid anywhere but doesn't tell us anything.
7577       if (i % Scale != 0) {
7578         // Each of the extended elements need to be zeroable.
7579         if (!Zeroable[i])
7580           return SDValue();
7581
7582         // We no longer are in the anyext case.
7583         AnyExt = false;
7584         continue;
7585       }
7586
7587       // Each of the base elements needs to be consecutive indices into the
7588       // same input vector.
7589       SDValue V = M < NumElements ? V1 : V2;
7590       M = M % NumElements;
7591       if (!InputV) {
7592         InputV = V;
7593         Offset = M - (i / Scale);
7594       } else if (InputV != V)
7595         return SDValue(); // Flip-flopping inputs.
7596
7597       // Offset must start in the lowest 128-bit lane or at the start of an
7598       // upper lane.
7599       // FIXME: Is it ever worth allowing a negative base offset?
7600       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7601             (Offset % NumEltsPerLane) == 0))
7602         return SDValue();
7603
7604       // If we are offsetting, all referenced entries must come from the same
7605       // lane.
7606       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7607         return SDValue();
7608
7609       if ((M % NumElements) != (Offset + (i / Scale)))
7610         return SDValue(); // Non-consecutive strided elements.
7611       Matches++;
7612     }
7613
7614     // If we fail to find an input, we have a zero-shuffle which should always
7615     // have already been handled.
7616     // FIXME: Maybe handle this here in case during blending we end up with one?
7617     if (!InputV)
7618       return SDValue();
7619
7620     // If we are offsetting, don't extend if we only match a single input, we
7621     // can always do better by using a basic PSHUF or PUNPCK.
7622     if (Offset != 0 && Matches < 2)
7623       return SDValue();
7624
7625     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7626         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7627   };
7628
7629   // The widest scale possible for extending is to a 64-bit integer.
7630   assert(Bits % 64 == 0 &&
7631          "The number of bits in a vector must be divisible by 64 on x86!");
7632   int NumExtElements = Bits / 64;
7633
7634   // Each iteration, try extending the elements half as much, but into twice as
7635   // many elements.
7636   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7637     assert(NumElements % NumExtElements == 0 &&
7638            "The input vector size must be divisible by the extended size.");
7639     if (SDValue V = Lower(NumElements / NumExtElements))
7640       return V;
7641   }
7642
7643   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7644   if (Bits != 128)
7645     return SDValue();
7646
7647   // Returns one of the source operands if the shuffle can be reduced to a
7648   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7649   auto CanZExtLowHalf = [&]() {
7650     for (int i = NumElements / 2; i != NumElements; ++i)
7651       if (!Zeroable[i])
7652         return SDValue();
7653     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7654       return V1;
7655     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7656       return V2;
7657     return SDValue();
7658   };
7659
7660   if (SDValue V = CanZExtLowHalf()) {
7661     V = DAG.getBitcast(MVT::v2i64, V);
7662     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7663     return DAG.getBitcast(VT, V);
7664   }
7665
7666   // No viable ext lowering found.
7667   return SDValue();
7668 }
7669
7670 /// \brief Try to get a scalar value for a specific element of a vector.
7671 ///
7672 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7673 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7674                                               SelectionDAG &DAG) {
7675   MVT VT = V.getSimpleValueType();
7676   MVT EltVT = VT.getVectorElementType();
7677   while (V.getOpcode() == ISD::BITCAST)
7678     V = V.getOperand(0);
7679   // If the bitcasts shift the element size, we can't extract an equivalent
7680   // element from it.
7681   MVT NewVT = V.getSimpleValueType();
7682   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7683     return SDValue();
7684
7685   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7686       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7687     // Ensure the scalar operand is the same size as the destination.
7688     // FIXME: Add support for scalar truncation where possible.
7689     SDValue S = V.getOperand(Idx);
7690     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7691       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7692   }
7693
7694   return SDValue();
7695 }
7696
7697 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7698 ///
7699 /// This is particularly important because the set of instructions varies
7700 /// significantly based on whether the operand is a load or not.
7701 static bool isShuffleFoldableLoad(SDValue V) {
7702   while (V.getOpcode() == ISD::BITCAST)
7703     V = V.getOperand(0);
7704
7705   return ISD::isNON_EXTLoad(V.getNode());
7706 }
7707
7708 /// \brief Try to lower insertion of a single element into a zero vector.
7709 ///
7710 /// This is a common pattern that we have especially efficient patterns to lower
7711 /// across all subtarget feature sets.
7712 static SDValue lowerVectorShuffleAsElementInsertion(
7713     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7714     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7715   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7716   MVT ExtVT = VT;
7717   MVT EltVT = VT.getVectorElementType();
7718
7719   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7720                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7721                 Mask.begin();
7722   bool IsV1Zeroable = true;
7723   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7724     if (i != V2Index && !Zeroable[i]) {
7725       IsV1Zeroable = false;
7726       break;
7727     }
7728
7729   // Check for a single input from a SCALAR_TO_VECTOR node.
7730   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7731   // all the smarts here sunk into that routine. However, the current
7732   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7733   // vector shuffle lowering is dead.
7734   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7735                                                DAG);
7736   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7737     // We need to zext the scalar if it is smaller than an i32.
7738     V2S = DAG.getBitcast(EltVT, V2S);
7739     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7740       // Using zext to expand a narrow element won't work for non-zero
7741       // insertions.
7742       if (!IsV1Zeroable)
7743         return SDValue();
7744
7745       // Zero-extend directly to i32.
7746       ExtVT = MVT::v4i32;
7747       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7748     }
7749     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7750   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7751              EltVT == MVT::i16) {
7752     // Either not inserting from the low element of the input or the input
7753     // element size is too small to use VZEXT_MOVL to clear the high bits.
7754     return SDValue();
7755   }
7756
7757   if (!IsV1Zeroable) {
7758     // If V1 can't be treated as a zero vector we have fewer options to lower
7759     // this. We can't support integer vectors or non-zero targets cheaply, and
7760     // the V1 elements can't be permuted in any way.
7761     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7762     if (!VT.isFloatingPoint() || V2Index != 0)
7763       return SDValue();
7764     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7765     V1Mask[V2Index] = -1;
7766     if (!isNoopShuffleMask(V1Mask))
7767       return SDValue();
7768     // This is essentially a special case blend operation, but if we have
7769     // general purpose blend operations, they are always faster. Bail and let
7770     // the rest of the lowering handle these as blends.
7771     if (Subtarget->hasSSE41())
7772       return SDValue();
7773
7774     // Otherwise, use MOVSD or MOVSS.
7775     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7776            "Only two types of floating point element types to handle!");
7777     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7778                        ExtVT, V1, V2);
7779   }
7780
7781   // This lowering only works for the low element with floating point vectors.
7782   if (VT.isFloatingPoint() && V2Index != 0)
7783     return SDValue();
7784
7785   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7786   if (ExtVT != VT)
7787     V2 = DAG.getBitcast(VT, V2);
7788
7789   if (V2Index != 0) {
7790     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7791     // the desired position. Otherwise it is more efficient to do a vector
7792     // shift left. We know that we can do a vector shift left because all
7793     // the inputs are zero.
7794     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7795       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7796       V2Shuffle[V2Index] = 0;
7797       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7798     } else {
7799       V2 = DAG.getBitcast(MVT::v2i64, V2);
7800       V2 = DAG.getNode(
7801           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7802           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7803                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7804                               DAG.getDataLayout(), VT)));
7805       V2 = DAG.getBitcast(VT, V2);
7806     }
7807   }
7808   return V2;
7809 }
7810
7811 /// \brief Try to lower broadcast of a single element.
7812 ///
7813 /// For convenience, this code also bundles all of the subtarget feature set
7814 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7815 /// a convenient way to factor it out.
7816 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7817                                              ArrayRef<int> Mask,
7818                                              const X86Subtarget *Subtarget,
7819                                              SelectionDAG &DAG) {
7820   if (!Subtarget->hasAVX())
7821     return SDValue();
7822   if (VT.isInteger() && !Subtarget->hasAVX2())
7823     return SDValue();
7824
7825   // Check that the mask is a broadcast.
7826   int BroadcastIdx = -1;
7827   for (int M : Mask)
7828     if (M >= 0 && BroadcastIdx == -1)
7829       BroadcastIdx = M;
7830     else if (M >= 0 && M != BroadcastIdx)
7831       return SDValue();
7832
7833   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7834                                             "a sorted mask where the broadcast "
7835                                             "comes from V1.");
7836
7837   // Go up the chain of (vector) values to find a scalar load that we can
7838   // combine with the broadcast.
7839   for (;;) {
7840     switch (V.getOpcode()) {
7841     case ISD::CONCAT_VECTORS: {
7842       int OperandSize = Mask.size() / V.getNumOperands();
7843       V = V.getOperand(BroadcastIdx / OperandSize);
7844       BroadcastIdx %= OperandSize;
7845       continue;
7846     }
7847
7848     case ISD::INSERT_SUBVECTOR: {
7849       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7850       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7851       if (!ConstantIdx)
7852         break;
7853
7854       int BeginIdx = (int)ConstantIdx->getZExtValue();
7855       int EndIdx =
7856           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7857       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7858         BroadcastIdx -= BeginIdx;
7859         V = VInner;
7860       } else {
7861         V = VOuter;
7862       }
7863       continue;
7864     }
7865     }
7866     break;
7867   }
7868
7869   // Check if this is a broadcast of a scalar. We special case lowering
7870   // for scalars so that we can more effectively fold with loads.
7871   // First, look through bitcast: if the original value has a larger element
7872   // type than the shuffle, the broadcast element is in essence truncated.
7873   // Make that explicit to ease folding.
7874   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7875     EVT EltVT = VT.getVectorElementType();
7876     SDValue V0 = V.getOperand(0);
7877     EVT V0VT = V0.getValueType();
7878
7879     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7880         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7881          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7882       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7883       BroadcastIdx = 0;
7884     }
7885   }
7886
7887   // Also check the simpler case, where we can directly reuse the scalar.
7888   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7889       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7890     V = V.getOperand(BroadcastIdx);
7891
7892     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7893     // Only AVX2 has register broadcasts.
7894     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7895       return SDValue();
7896   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7897     // We can't broadcast from a vector register without AVX2, and we can only
7898     // broadcast from the zero-element of a vector register.
7899     return SDValue();
7900   }
7901
7902   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7903 }
7904
7905 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7906 // INSERTPS when the V1 elements are already in the correct locations
7907 // because otherwise we can just always use two SHUFPS instructions which
7908 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7909 // perform INSERTPS if a single V1 element is out of place and all V2
7910 // elements are zeroable.
7911 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7912                                             ArrayRef<int> Mask,
7913                                             SelectionDAG &DAG) {
7914   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7915   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7916   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7917   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7918
7919   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7920
7921   unsigned ZMask = 0;
7922   int V1DstIndex = -1;
7923   int V2DstIndex = -1;
7924   bool V1UsedInPlace = false;
7925
7926   for (int i = 0; i < 4; ++i) {
7927     // Synthesize a zero mask from the zeroable elements (includes undefs).
7928     if (Zeroable[i]) {
7929       ZMask |= 1 << i;
7930       continue;
7931     }
7932
7933     // Flag if we use any V1 inputs in place.
7934     if (i == Mask[i]) {
7935       V1UsedInPlace = true;
7936       continue;
7937     }
7938
7939     // We can only insert a single non-zeroable element.
7940     if (V1DstIndex != -1 || V2DstIndex != -1)
7941       return SDValue();
7942
7943     if (Mask[i] < 4) {
7944       // V1 input out of place for insertion.
7945       V1DstIndex = i;
7946     } else {
7947       // V2 input for insertion.
7948       V2DstIndex = i;
7949     }
7950   }
7951
7952   // Don't bother if we have no (non-zeroable) element for insertion.
7953   if (V1DstIndex == -1 && V2DstIndex == -1)
7954     return SDValue();
7955
7956   // Determine element insertion src/dst indices. The src index is from the
7957   // start of the inserted vector, not the start of the concatenated vector.
7958   unsigned V2SrcIndex = 0;
7959   if (V1DstIndex != -1) {
7960     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7961     // and don't use the original V2 at all.
7962     V2SrcIndex = Mask[V1DstIndex];
7963     V2DstIndex = V1DstIndex;
7964     V2 = V1;
7965   } else {
7966     V2SrcIndex = Mask[V2DstIndex] - 4;
7967   }
7968
7969   // If no V1 inputs are used in place, then the result is created only from
7970   // the zero mask and the V2 insertion - so remove V1 dependency.
7971   if (!V1UsedInPlace)
7972     V1 = DAG.getUNDEF(MVT::v4f32);
7973
7974   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7975   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7976
7977   // Insert the V2 element into the desired position.
7978   SDLoc DL(Op);
7979   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7980                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7981 }
7982
7983 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7984 /// UNPCK instruction.
7985 ///
7986 /// This specifically targets cases where we end up with alternating between
7987 /// the two inputs, and so can permute them into something that feeds a single
7988 /// UNPCK instruction. Note that this routine only targets integer vectors
7989 /// because for floating point vectors we have a generalized SHUFPS lowering
7990 /// strategy that handles everything that doesn't *exactly* match an unpack,
7991 /// making this clever lowering unnecessary.
7992 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7993                                                     SDValue V1, SDValue V2,
7994                                                     ArrayRef<int> Mask,
7995                                                     SelectionDAG &DAG) {
7996   assert(!VT.isFloatingPoint() &&
7997          "This routine only supports integer vectors.");
7998   assert(!isSingleInputShuffleMask(Mask) &&
7999          "This routine should only be used when blending two inputs.");
8000   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8001
8002   int Size = Mask.size();
8003
8004   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8005     return M >= 0 && M % Size < Size / 2;
8006   });
8007   int NumHiInputs = std::count_if(
8008       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8009
8010   bool UnpackLo = NumLoInputs >= NumHiInputs;
8011
8012   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8013     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8014     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8015
8016     for (int i = 0; i < Size; ++i) {
8017       if (Mask[i] < 0)
8018         continue;
8019
8020       // Each element of the unpack contains Scale elements from this mask.
8021       int UnpackIdx = i / Scale;
8022
8023       // We only handle the case where V1 feeds the first slots of the unpack.
8024       // We rely on canonicalization to ensure this is the case.
8025       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8026         return SDValue();
8027
8028       // Setup the mask for this input. The indexing is tricky as we have to
8029       // handle the unpack stride.
8030       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8031       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8032           Mask[i] % Size;
8033     }
8034
8035     // If we will have to shuffle both inputs to use the unpack, check whether
8036     // we can just unpack first and shuffle the result. If so, skip this unpack.
8037     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8038         !isNoopShuffleMask(V2Mask))
8039       return SDValue();
8040
8041     // Shuffle the inputs into place.
8042     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8043     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8044
8045     // Cast the inputs to the type we will use to unpack them.
8046     V1 = DAG.getBitcast(UnpackVT, V1);
8047     V2 = DAG.getBitcast(UnpackVT, V2);
8048
8049     // Unpack the inputs and cast the result back to the desired type.
8050     return DAG.getBitcast(
8051         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8052                         UnpackVT, V1, V2));
8053   };
8054
8055   // We try each unpack from the largest to the smallest to try and find one
8056   // that fits this mask.
8057   int OrigNumElements = VT.getVectorNumElements();
8058   int OrigScalarSize = VT.getScalarSizeInBits();
8059   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8060     int Scale = ScalarSize / OrigScalarSize;
8061     int NumElements = OrigNumElements / Scale;
8062     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8063     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8064       return Unpack;
8065   }
8066
8067   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8068   // initial unpack.
8069   if (NumLoInputs == 0 || NumHiInputs == 0) {
8070     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8071            "We have to have *some* inputs!");
8072     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8073
8074     // FIXME: We could consider the total complexity of the permute of each
8075     // possible unpacking. Or at the least we should consider how many
8076     // half-crossings are created.
8077     // FIXME: We could consider commuting the unpacks.
8078
8079     SmallVector<int, 32> PermMask;
8080     PermMask.assign(Size, -1);
8081     for (int i = 0; i < Size; ++i) {
8082       if (Mask[i] < 0)
8083         continue;
8084
8085       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8086
8087       PermMask[i] =
8088           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8089     }
8090     return DAG.getVectorShuffle(
8091         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8092                             DL, VT, V1, V2),
8093         DAG.getUNDEF(VT), PermMask);
8094   }
8095
8096   return SDValue();
8097 }
8098
8099 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8100 ///
8101 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8102 /// support for floating point shuffles but not integer shuffles. These
8103 /// instructions will incur a domain crossing penalty on some chips though so
8104 /// it is better to avoid lowering through this for integer vectors where
8105 /// possible.
8106 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8107                                        const X86Subtarget *Subtarget,
8108                                        SelectionDAG &DAG) {
8109   SDLoc DL(Op);
8110   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8111   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8112   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8113   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8114   ArrayRef<int> Mask = SVOp->getMask();
8115   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8116
8117   if (isSingleInputShuffleMask(Mask)) {
8118     // Use low duplicate instructions for masks that match their pattern.
8119     if (Subtarget->hasSSE3())
8120       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8121         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8122
8123     // Straight shuffle of a single input vector. Simulate this by using the
8124     // single input as both of the "inputs" to this instruction..
8125     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8126
8127     if (Subtarget->hasAVX()) {
8128       // If we have AVX, we can use VPERMILPS which will allow folding a load
8129       // into the shuffle.
8130       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8131                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8132     }
8133
8134     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8135                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8136   }
8137   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8138   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8139
8140   // If we have a single input, insert that into V1 if we can do so cheaply.
8141   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8142     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8143             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8144       return Insertion;
8145     // Try inverting the insertion since for v2 masks it is easy to do and we
8146     // can't reliably sort the mask one way or the other.
8147     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8148                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8149     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8150             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8151       return Insertion;
8152   }
8153
8154   // Try to use one of the special instruction patterns to handle two common
8155   // blend patterns if a zero-blend above didn't work.
8156   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8157       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8158     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8159       // We can either use a special instruction to load over the low double or
8160       // to move just the low double.
8161       return DAG.getNode(
8162           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8163           DL, MVT::v2f64, V2,
8164           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8165
8166   if (Subtarget->hasSSE41())
8167     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8168                                                   Subtarget, DAG))
8169       return Blend;
8170
8171   // Use dedicated unpack instructions for masks that match their pattern.
8172   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8173     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8174   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8175     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8176
8177   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8178   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8179                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8180 }
8181
8182 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8183 ///
8184 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8185 /// the integer unit to minimize domain crossing penalties. However, for blends
8186 /// it falls back to the floating point shuffle operation with appropriate bit
8187 /// casting.
8188 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8189                                        const X86Subtarget *Subtarget,
8190                                        SelectionDAG &DAG) {
8191   SDLoc DL(Op);
8192   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8193   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8194   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8195   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8196   ArrayRef<int> Mask = SVOp->getMask();
8197   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8198
8199   if (isSingleInputShuffleMask(Mask)) {
8200     // Check for being able to broadcast a single element.
8201     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8202                                                           Mask, Subtarget, DAG))
8203       return Broadcast;
8204
8205     // Straight shuffle of a single input vector. For everything from SSE2
8206     // onward this has a single fast instruction with no scary immediates.
8207     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8208     V1 = DAG.getBitcast(MVT::v4i32, V1);
8209     int WidenedMask[4] = {
8210         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8211         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8212     return DAG.getBitcast(
8213         MVT::v2i64,
8214         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8215                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8216   }
8217   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8218   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8219   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8220   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8221
8222   // If we have a blend of two PACKUS operations an the blend aligns with the
8223   // low and half halves, we can just merge the PACKUS operations. This is
8224   // particularly important as it lets us merge shuffles that this routine itself
8225   // creates.
8226   auto GetPackNode = [](SDValue V) {
8227     while (V.getOpcode() == ISD::BITCAST)
8228       V = V.getOperand(0);
8229
8230     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8231   };
8232   if (SDValue V1Pack = GetPackNode(V1))
8233     if (SDValue V2Pack = GetPackNode(V2))
8234       return DAG.getBitcast(MVT::v2i64,
8235                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8236                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8237                                                      : V1Pack.getOperand(1),
8238                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8239                                                      : V2Pack.getOperand(1)));
8240
8241   // Try to use shift instructions.
8242   if (SDValue Shift =
8243           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8244     return Shift;
8245
8246   // When loading a scalar and then shuffling it into a vector we can often do
8247   // the insertion cheaply.
8248   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8249           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8250     return Insertion;
8251   // Try inverting the insertion since for v2 masks it is easy to do and we
8252   // can't reliably sort the mask one way or the other.
8253   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8254   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8255           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8256     return Insertion;
8257
8258   // We have different paths for blend lowering, but they all must use the
8259   // *exact* same predicate.
8260   bool IsBlendSupported = Subtarget->hasSSE41();
8261   if (IsBlendSupported)
8262     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8263                                                   Subtarget, DAG))
8264       return Blend;
8265
8266   // Use dedicated unpack instructions for masks that match their pattern.
8267   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8268     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8269   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8270     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8271
8272   // Try to use byte rotation instructions.
8273   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8274   if (Subtarget->hasSSSE3())
8275     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8276             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8277       return Rotate;
8278
8279   // If we have direct support for blends, we should lower by decomposing into
8280   // a permute. That will be faster than the domain cross.
8281   if (IsBlendSupported)
8282     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8283                                                       Mask, DAG);
8284
8285   // We implement this with SHUFPD which is pretty lame because it will likely
8286   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8287   // However, all the alternatives are still more cycles and newer chips don't
8288   // have this problem. It would be really nice if x86 had better shuffles here.
8289   V1 = DAG.getBitcast(MVT::v2f64, V1);
8290   V2 = DAG.getBitcast(MVT::v2f64, V2);
8291   return DAG.getBitcast(MVT::v2i64,
8292                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8293 }
8294
8295 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8296 ///
8297 /// This is used to disable more specialized lowerings when the shufps lowering
8298 /// will happen to be efficient.
8299 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8300   // This routine only handles 128-bit shufps.
8301   assert(Mask.size() == 4 && "Unsupported mask size!");
8302
8303   // To lower with a single SHUFPS we need to have the low half and high half
8304   // each requiring a single input.
8305   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8306     return false;
8307   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8308     return false;
8309
8310   return true;
8311 }
8312
8313 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8314 ///
8315 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8316 /// It makes no assumptions about whether this is the *best* lowering, it simply
8317 /// uses it.
8318 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8319                                             ArrayRef<int> Mask, SDValue V1,
8320                                             SDValue V2, SelectionDAG &DAG) {
8321   SDValue LowV = V1, HighV = V2;
8322   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8323
8324   int NumV2Elements =
8325       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8326
8327   if (NumV2Elements == 1) {
8328     int V2Index =
8329         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8330         Mask.begin();
8331
8332     // Compute the index adjacent to V2Index and in the same half by toggling
8333     // the low bit.
8334     int V2AdjIndex = V2Index ^ 1;
8335
8336     if (Mask[V2AdjIndex] == -1) {
8337       // Handles all the cases where we have a single V2 element and an undef.
8338       // This will only ever happen in the high lanes because we commute the
8339       // vector otherwise.
8340       if (V2Index < 2)
8341         std::swap(LowV, HighV);
8342       NewMask[V2Index] -= 4;
8343     } else {
8344       // Handle the case where the V2 element ends up adjacent to a V1 element.
8345       // To make this work, blend them together as the first step.
8346       int V1Index = V2AdjIndex;
8347       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8348       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8349                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8350
8351       // Now proceed to reconstruct the final blend as we have the necessary
8352       // high or low half formed.
8353       if (V2Index < 2) {
8354         LowV = V2;
8355         HighV = V1;
8356       } else {
8357         HighV = V2;
8358       }
8359       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8360       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8361     }
8362   } else if (NumV2Elements == 2) {
8363     if (Mask[0] < 4 && Mask[1] < 4) {
8364       // Handle the easy case where we have V1 in the low lanes and V2 in the
8365       // high lanes.
8366       NewMask[2] -= 4;
8367       NewMask[3] -= 4;
8368     } else if (Mask[2] < 4 && Mask[3] < 4) {
8369       // We also handle the reversed case because this utility may get called
8370       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8371       // arrange things in the right direction.
8372       NewMask[0] -= 4;
8373       NewMask[1] -= 4;
8374       HighV = V1;
8375       LowV = V2;
8376     } else {
8377       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8378       // trying to place elements directly, just blend them and set up the final
8379       // shuffle to place them.
8380
8381       // The first two blend mask elements are for V1, the second two are for
8382       // V2.
8383       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8384                           Mask[2] < 4 ? Mask[2] : Mask[3],
8385                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8386                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8387       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8388                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8389
8390       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8391       // a blend.
8392       LowV = HighV = V1;
8393       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8394       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8395       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8396       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8397     }
8398   }
8399   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8400                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8401 }
8402
8403 /// \brief Lower 4-lane 32-bit floating point shuffles.
8404 ///
8405 /// Uses instructions exclusively from the floating point unit to minimize
8406 /// domain crossing penalties, as these are sufficient to implement all v4f32
8407 /// shuffles.
8408 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8409                                        const X86Subtarget *Subtarget,
8410                                        SelectionDAG &DAG) {
8411   SDLoc DL(Op);
8412   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8413   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8414   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8415   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8416   ArrayRef<int> Mask = SVOp->getMask();
8417   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8418
8419   int NumV2Elements =
8420       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8421
8422   if (NumV2Elements == 0) {
8423     // Check for being able to broadcast a single element.
8424     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8425                                                           Mask, Subtarget, DAG))
8426       return Broadcast;
8427
8428     // Use even/odd duplicate instructions for masks that match their pattern.
8429     if (Subtarget->hasSSE3()) {
8430       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8431         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8432       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8433         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8434     }
8435
8436     if (Subtarget->hasAVX()) {
8437       // If we have AVX, we can use VPERMILPS which will allow folding a load
8438       // into the shuffle.
8439       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8440                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8441     }
8442
8443     // Otherwise, use a straight shuffle of a single input vector. We pass the
8444     // input vector to both operands to simulate this with a SHUFPS.
8445     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8446                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8447   }
8448
8449   // There are special ways we can lower some single-element blends. However, we
8450   // have custom ways we can lower more complex single-element blends below that
8451   // we defer to if both this and BLENDPS fail to match, so restrict this to
8452   // when the V2 input is targeting element 0 of the mask -- that is the fast
8453   // case here.
8454   if (NumV2Elements == 1 && Mask[0] >= 4)
8455     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8456                                                          Mask, Subtarget, DAG))
8457       return V;
8458
8459   if (Subtarget->hasSSE41()) {
8460     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8461                                                   Subtarget, DAG))
8462       return Blend;
8463
8464     // Use INSERTPS if we can complete the shuffle efficiently.
8465     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8466       return V;
8467
8468     if (!isSingleSHUFPSMask(Mask))
8469       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8470               DL, MVT::v4f32, V1, V2, Mask, DAG))
8471         return BlendPerm;
8472   }
8473
8474   // Use dedicated unpack instructions for masks that match their pattern.
8475   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8476     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8477   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8478     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8479   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8480     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8481   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8482     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8483
8484   // Otherwise fall back to a SHUFPS lowering strategy.
8485   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8486 }
8487
8488 /// \brief Lower 4-lane i32 vector shuffles.
8489 ///
8490 /// We try to handle these with integer-domain shuffles where we can, but for
8491 /// blends we use the floating point domain blend instructions.
8492 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8493                                        const X86Subtarget *Subtarget,
8494                                        SelectionDAG &DAG) {
8495   SDLoc DL(Op);
8496   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8497   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8498   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8499   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8500   ArrayRef<int> Mask = SVOp->getMask();
8501   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8502
8503   // Whenever we can lower this as a zext, that instruction is strictly faster
8504   // than any alternative. It also allows us to fold memory operands into the
8505   // shuffle in many cases.
8506   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8507                                                          Mask, Subtarget, DAG))
8508     return ZExt;
8509
8510   int NumV2Elements =
8511       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8512
8513   if (NumV2Elements == 0) {
8514     // Check for being able to broadcast a single element.
8515     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8516                                                           Mask, Subtarget, DAG))
8517       return Broadcast;
8518
8519     // Straight shuffle of a single input vector. For everything from SSE2
8520     // onward this has a single fast instruction with no scary immediates.
8521     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8522     // but we aren't actually going to use the UNPCK instruction because doing
8523     // so prevents folding a load into this instruction or making a copy.
8524     const int UnpackLoMask[] = {0, 0, 1, 1};
8525     const int UnpackHiMask[] = {2, 2, 3, 3};
8526     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8527       Mask = UnpackLoMask;
8528     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8529       Mask = UnpackHiMask;
8530
8531     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8532                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8533   }
8534
8535   // Try to use shift instructions.
8536   if (SDValue Shift =
8537           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8538     return Shift;
8539
8540   // There are special ways we can lower some single-element blends.
8541   if (NumV2Elements == 1)
8542     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8543                                                          Mask, Subtarget, DAG))
8544       return V;
8545
8546   // We have different paths for blend lowering, but they all must use the
8547   // *exact* same predicate.
8548   bool IsBlendSupported = Subtarget->hasSSE41();
8549   if (IsBlendSupported)
8550     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8551                                                   Subtarget, DAG))
8552       return Blend;
8553
8554   if (SDValue Masked =
8555           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8556     return Masked;
8557
8558   // Use dedicated unpack instructions for masks that match their pattern.
8559   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8560     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8561   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8562     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8563   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8564     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8565   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8566     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8567
8568   // Try to use byte rotation instructions.
8569   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8570   if (Subtarget->hasSSSE3())
8571     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8572             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8573       return Rotate;
8574
8575   // If we have direct support for blends, we should lower by decomposing into
8576   // a permute. That will be faster than the domain cross.
8577   if (IsBlendSupported)
8578     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8579                                                       Mask, DAG);
8580
8581   // Try to lower by permuting the inputs into an unpack instruction.
8582   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8583                                                             V2, Mask, DAG))
8584     return Unpack;
8585
8586   // We implement this with SHUFPS because it can blend from two vectors.
8587   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8588   // up the inputs, bypassing domain shift penalties that we would encur if we
8589   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8590   // relevant.
8591   return DAG.getBitcast(
8592       MVT::v4i32,
8593       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8594                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8595 }
8596
8597 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8598 /// shuffle lowering, and the most complex part.
8599 ///
8600 /// The lowering strategy is to try to form pairs of input lanes which are
8601 /// targeted at the same half of the final vector, and then use a dword shuffle
8602 /// to place them onto the right half, and finally unpack the paired lanes into
8603 /// their final position.
8604 ///
8605 /// The exact breakdown of how to form these dword pairs and align them on the
8606 /// correct sides is really tricky. See the comments within the function for
8607 /// more of the details.
8608 ///
8609 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8610 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8611 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8612 /// vector, form the analogous 128-bit 8-element Mask.
8613 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8614     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8615     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8616   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8617   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8618
8619   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8620   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8621   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8622
8623   SmallVector<int, 4> LoInputs;
8624   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8625                [](int M) { return M >= 0; });
8626   std::sort(LoInputs.begin(), LoInputs.end());
8627   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8628   SmallVector<int, 4> HiInputs;
8629   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8630                [](int M) { return M >= 0; });
8631   std::sort(HiInputs.begin(), HiInputs.end());
8632   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8633   int NumLToL =
8634       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8635   int NumHToL = LoInputs.size() - NumLToL;
8636   int NumLToH =
8637       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8638   int NumHToH = HiInputs.size() - NumLToH;
8639   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8640   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8641   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8642   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8643
8644   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8645   // such inputs we can swap two of the dwords across the half mark and end up
8646   // with <=2 inputs to each half in each half. Once there, we can fall through
8647   // to the generic code below. For example:
8648   //
8649   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8650   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8651   //
8652   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8653   // and an existing 2-into-2 on the other half. In this case we may have to
8654   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8655   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8656   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8657   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8658   // half than the one we target for fixing) will be fixed when we re-enter this
8659   // path. We will also combine away any sequence of PSHUFD instructions that
8660   // result into a single instruction. Here is an example of the tricky case:
8661   //
8662   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8663   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8664   //
8665   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8666   //
8667   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8668   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8669   //
8670   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8671   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8672   //
8673   // The result is fine to be handled by the generic logic.
8674   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8675                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8676                           int AOffset, int BOffset) {
8677     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8678            "Must call this with A having 3 or 1 inputs from the A half.");
8679     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8680            "Must call this with B having 1 or 3 inputs from the B half.");
8681     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8682            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8683
8684     bool ThreeAInputs = AToAInputs.size() == 3;
8685
8686     // Compute the index of dword with only one word among the three inputs in
8687     // a half by taking the sum of the half with three inputs and subtracting
8688     // the sum of the actual three inputs. The difference is the remaining
8689     // slot.
8690     int ADWord, BDWord;
8691     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8692     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8693     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8694     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8695     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8696     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8697     int TripleNonInputIdx =
8698         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8699     TripleDWord = TripleNonInputIdx / 2;
8700
8701     // We use xor with one to compute the adjacent DWord to whichever one the
8702     // OneInput is in.
8703     OneInputDWord = (OneInput / 2) ^ 1;
8704
8705     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8706     // and BToA inputs. If there is also such a problem with the BToB and AToB
8707     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8708     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8709     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8710     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8711       // Compute how many inputs will be flipped by swapping these DWords. We
8712       // need
8713       // to balance this to ensure we don't form a 3-1 shuffle in the other
8714       // half.
8715       int NumFlippedAToBInputs =
8716           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8717           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8718       int NumFlippedBToBInputs =
8719           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8720           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8721       if ((NumFlippedAToBInputs == 1 &&
8722            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8723           (NumFlippedBToBInputs == 1 &&
8724            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8725         // We choose whether to fix the A half or B half based on whether that
8726         // half has zero flipped inputs. At zero, we may not be able to fix it
8727         // with that half. We also bias towards fixing the B half because that
8728         // will more commonly be the high half, and we have to bias one way.
8729         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8730                                                        ArrayRef<int> Inputs) {
8731           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8732           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8733                                          PinnedIdx ^ 1) != Inputs.end();
8734           // Determine whether the free index is in the flipped dword or the
8735           // unflipped dword based on where the pinned index is. We use this bit
8736           // in an xor to conditionally select the adjacent dword.
8737           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8738           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8739                                              FixFreeIdx) != Inputs.end();
8740           if (IsFixIdxInput == IsFixFreeIdxInput)
8741             FixFreeIdx += 1;
8742           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8743                                         FixFreeIdx) != Inputs.end();
8744           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8745                  "We need to be changing the number of flipped inputs!");
8746           int PSHUFHalfMask[] = {0, 1, 2, 3};
8747           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8748           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8749                           MVT::v8i16, V,
8750                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8751
8752           for (int &M : Mask)
8753             if (M != -1 && M == FixIdx)
8754               M = FixFreeIdx;
8755             else if (M != -1 && M == FixFreeIdx)
8756               M = FixIdx;
8757         };
8758         if (NumFlippedBToBInputs != 0) {
8759           int BPinnedIdx =
8760               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8761           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8762         } else {
8763           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8764           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8765           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8766         }
8767       }
8768     }
8769
8770     int PSHUFDMask[] = {0, 1, 2, 3};
8771     PSHUFDMask[ADWord] = BDWord;
8772     PSHUFDMask[BDWord] = ADWord;
8773     V = DAG.getBitcast(
8774         VT,
8775         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8776                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8777
8778     // Adjust the mask to match the new locations of A and B.
8779     for (int &M : Mask)
8780       if (M != -1 && M/2 == ADWord)
8781         M = 2 * BDWord + M % 2;
8782       else if (M != -1 && M/2 == BDWord)
8783         M = 2 * ADWord + M % 2;
8784
8785     // Recurse back into this routine to re-compute state now that this isn't
8786     // a 3 and 1 problem.
8787     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8788                                                      DAG);
8789   };
8790   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8791     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8792   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8793     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8794
8795   // At this point there are at most two inputs to the low and high halves from
8796   // each half. That means the inputs can always be grouped into dwords and
8797   // those dwords can then be moved to the correct half with a dword shuffle.
8798   // We use at most one low and one high word shuffle to collect these paired
8799   // inputs into dwords, and finally a dword shuffle to place them.
8800   int PSHUFLMask[4] = {-1, -1, -1, -1};
8801   int PSHUFHMask[4] = {-1, -1, -1, -1};
8802   int PSHUFDMask[4] = {-1, -1, -1, -1};
8803
8804   // First fix the masks for all the inputs that are staying in their
8805   // original halves. This will then dictate the targets of the cross-half
8806   // shuffles.
8807   auto fixInPlaceInputs =
8808       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8809                     MutableArrayRef<int> SourceHalfMask,
8810                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8811     if (InPlaceInputs.empty())
8812       return;
8813     if (InPlaceInputs.size() == 1) {
8814       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8815           InPlaceInputs[0] - HalfOffset;
8816       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8817       return;
8818     }
8819     if (IncomingInputs.empty()) {
8820       // Just fix all of the in place inputs.
8821       for (int Input : InPlaceInputs) {
8822         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8823         PSHUFDMask[Input / 2] = Input / 2;
8824       }
8825       return;
8826     }
8827
8828     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8829     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8830         InPlaceInputs[0] - HalfOffset;
8831     // Put the second input next to the first so that they are packed into
8832     // a dword. We find the adjacent index by toggling the low bit.
8833     int AdjIndex = InPlaceInputs[0] ^ 1;
8834     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8835     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8836     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8837   };
8838   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8839   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8840
8841   // Now gather the cross-half inputs and place them into a free dword of
8842   // their target half.
8843   // FIXME: This operation could almost certainly be simplified dramatically to
8844   // look more like the 3-1 fixing operation.
8845   auto moveInputsToRightHalf = [&PSHUFDMask](
8846       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8847       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8848       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8849       int DestOffset) {
8850     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8851       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8852     };
8853     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8854                                                int Word) {
8855       int LowWord = Word & ~1;
8856       int HighWord = Word | 1;
8857       return isWordClobbered(SourceHalfMask, LowWord) ||
8858              isWordClobbered(SourceHalfMask, HighWord);
8859     };
8860
8861     if (IncomingInputs.empty())
8862       return;
8863
8864     if (ExistingInputs.empty()) {
8865       // Map any dwords with inputs from them into the right half.
8866       for (int Input : IncomingInputs) {
8867         // If the source half mask maps over the inputs, turn those into
8868         // swaps and use the swapped lane.
8869         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8870           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8871             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8872                 Input - SourceOffset;
8873             // We have to swap the uses in our half mask in one sweep.
8874             for (int &M : HalfMask)
8875               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8876                 M = Input;
8877               else if (M == Input)
8878                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8879           } else {
8880             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8881                        Input - SourceOffset &&
8882                    "Previous placement doesn't match!");
8883           }
8884           // Note that this correctly re-maps both when we do a swap and when
8885           // we observe the other side of the swap above. We rely on that to
8886           // avoid swapping the members of the input list directly.
8887           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8888         }
8889
8890         // Map the input's dword into the correct half.
8891         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8892           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8893         else
8894           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8895                      Input / 2 &&
8896                  "Previous placement doesn't match!");
8897       }
8898
8899       // And just directly shift any other-half mask elements to be same-half
8900       // as we will have mirrored the dword containing the element into the
8901       // same position within that half.
8902       for (int &M : HalfMask)
8903         if (M >= SourceOffset && M < SourceOffset + 4) {
8904           M = M - SourceOffset + DestOffset;
8905           assert(M >= 0 && "This should never wrap below zero!");
8906         }
8907       return;
8908     }
8909
8910     // Ensure we have the input in a viable dword of its current half. This
8911     // is particularly tricky because the original position may be clobbered
8912     // by inputs being moved and *staying* in that half.
8913     if (IncomingInputs.size() == 1) {
8914       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8915         int InputFixed = std::find(std::begin(SourceHalfMask),
8916                                    std::end(SourceHalfMask), -1) -
8917                          std::begin(SourceHalfMask) + SourceOffset;
8918         SourceHalfMask[InputFixed - SourceOffset] =
8919             IncomingInputs[0] - SourceOffset;
8920         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8921                      InputFixed);
8922         IncomingInputs[0] = InputFixed;
8923       }
8924     } else if (IncomingInputs.size() == 2) {
8925       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8926           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8927         // We have two non-adjacent or clobbered inputs we need to extract from
8928         // the source half. To do this, we need to map them into some adjacent
8929         // dword slot in the source mask.
8930         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8931                               IncomingInputs[1] - SourceOffset};
8932
8933         // If there is a free slot in the source half mask adjacent to one of
8934         // the inputs, place the other input in it. We use (Index XOR 1) to
8935         // compute an adjacent index.
8936         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8937             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8938           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8939           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8940           InputsFixed[1] = InputsFixed[0] ^ 1;
8941         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8942                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8943           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8944           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8945           InputsFixed[0] = InputsFixed[1] ^ 1;
8946         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8947                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8948           // The two inputs are in the same DWord but it is clobbered and the
8949           // adjacent DWord isn't used at all. Move both inputs to the free
8950           // slot.
8951           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8952           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8953           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8954           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8955         } else {
8956           // The only way we hit this point is if there is no clobbering
8957           // (because there are no off-half inputs to this half) and there is no
8958           // free slot adjacent to one of the inputs. In this case, we have to
8959           // swap an input with a non-input.
8960           for (int i = 0; i < 4; ++i)
8961             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8962                    "We can't handle any clobbers here!");
8963           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8964                  "Cannot have adjacent inputs here!");
8965
8966           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8967           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8968
8969           // We also have to update the final source mask in this case because
8970           // it may need to undo the above swap.
8971           for (int &M : FinalSourceHalfMask)
8972             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8973               M = InputsFixed[1] + SourceOffset;
8974             else if (M == InputsFixed[1] + SourceOffset)
8975               M = (InputsFixed[0] ^ 1) + SourceOffset;
8976
8977           InputsFixed[1] = InputsFixed[0] ^ 1;
8978         }
8979
8980         // Point everything at the fixed inputs.
8981         for (int &M : HalfMask)
8982           if (M == IncomingInputs[0])
8983             M = InputsFixed[0] + SourceOffset;
8984           else if (M == IncomingInputs[1])
8985             M = InputsFixed[1] + SourceOffset;
8986
8987         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8988         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8989       }
8990     } else {
8991       llvm_unreachable("Unhandled input size!");
8992     }
8993
8994     // Now hoist the DWord down to the right half.
8995     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8996     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8997     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8998     for (int &M : HalfMask)
8999       for (int Input : IncomingInputs)
9000         if (M == Input)
9001           M = FreeDWord * 2 + Input % 2;
9002   };
9003   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9004                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9005   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9006                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9007
9008   // Now enact all the shuffles we've computed to move the inputs into their
9009   // target half.
9010   if (!isNoopShuffleMask(PSHUFLMask))
9011     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9012                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9013   if (!isNoopShuffleMask(PSHUFHMask))
9014     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9015                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9016   if (!isNoopShuffleMask(PSHUFDMask))
9017     V = DAG.getBitcast(
9018         VT,
9019         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9020                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9021
9022   // At this point, each half should contain all its inputs, and we can then
9023   // just shuffle them into their final position.
9024   assert(std::count_if(LoMask.begin(), LoMask.end(),
9025                        [](int M) { return M >= 4; }) == 0 &&
9026          "Failed to lift all the high half inputs to the low mask!");
9027   assert(std::count_if(HiMask.begin(), HiMask.end(),
9028                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9029          "Failed to lift all the low half inputs to the high mask!");
9030
9031   // Do a half shuffle for the low mask.
9032   if (!isNoopShuffleMask(LoMask))
9033     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9034                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9035
9036   // Do a half shuffle with the high mask after shifting its values down.
9037   for (int &M : HiMask)
9038     if (M >= 0)
9039       M -= 4;
9040   if (!isNoopShuffleMask(HiMask))
9041     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9042                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9043
9044   return V;
9045 }
9046
9047 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9048 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9049                                           SDValue V2, ArrayRef<int> Mask,
9050                                           SelectionDAG &DAG, bool &V1InUse,
9051                                           bool &V2InUse) {
9052   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9053   SDValue V1Mask[16];
9054   SDValue V2Mask[16];
9055   V1InUse = false;
9056   V2InUse = false;
9057
9058   int Size = Mask.size();
9059   int Scale = 16 / Size;
9060   for (int i = 0; i < 16; ++i) {
9061     if (Mask[i / Scale] == -1) {
9062       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9063     } else {
9064       const int ZeroMask = 0x80;
9065       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9066                                           : ZeroMask;
9067       int V2Idx = Mask[i / Scale] < Size
9068                       ? ZeroMask
9069                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9070       if (Zeroable[i / Scale])
9071         V1Idx = V2Idx = ZeroMask;
9072       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9073       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9074       V1InUse |= (ZeroMask != V1Idx);
9075       V2InUse |= (ZeroMask != V2Idx);
9076     }
9077   }
9078
9079   if (V1InUse)
9080     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9081                      DAG.getBitcast(MVT::v16i8, V1),
9082                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9083   if (V2InUse)
9084     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9085                      DAG.getBitcast(MVT::v16i8, V2),
9086                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9087
9088   // If we need shuffled inputs from both, blend the two.
9089   SDValue V;
9090   if (V1InUse && V2InUse)
9091     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9092   else
9093     V = V1InUse ? V1 : V2;
9094
9095   // Cast the result back to the correct type.
9096   return DAG.getBitcast(VT, V);
9097 }
9098
9099 /// \brief Generic lowering of 8-lane i16 shuffles.
9100 ///
9101 /// This handles both single-input shuffles and combined shuffle/blends with
9102 /// two inputs. The single input shuffles are immediately delegated to
9103 /// a dedicated lowering routine.
9104 ///
9105 /// The blends are lowered in one of three fundamental ways. If there are few
9106 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9107 /// of the input is significantly cheaper when lowered as an interleaving of
9108 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9109 /// halves of the inputs separately (making them have relatively few inputs)
9110 /// and then concatenate them.
9111 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9112                                        const X86Subtarget *Subtarget,
9113                                        SelectionDAG &DAG) {
9114   SDLoc DL(Op);
9115   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9116   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9117   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9118   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9119   ArrayRef<int> OrigMask = SVOp->getMask();
9120   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9121                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9122   MutableArrayRef<int> Mask(MaskStorage);
9123
9124   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9125
9126   // Whenever we can lower this as a zext, that instruction is strictly faster
9127   // than any alternative.
9128   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9129           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9130     return ZExt;
9131
9132   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9133   (void)isV1;
9134   auto isV2 = [](int M) { return M >= 8; };
9135
9136   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9137
9138   if (NumV2Inputs == 0) {
9139     // Check for being able to broadcast a single element.
9140     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9141                                                           Mask, Subtarget, DAG))
9142       return Broadcast;
9143
9144     // Try to use shift instructions.
9145     if (SDValue Shift =
9146             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9147       return Shift;
9148
9149     // Use dedicated unpack instructions for masks that match their pattern.
9150     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9151       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9152     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9153       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9154
9155     // Try to use byte rotation instructions.
9156     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9157                                                         Mask, Subtarget, DAG))
9158       return Rotate;
9159
9160     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9161                                                      Subtarget, DAG);
9162   }
9163
9164   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9165          "All single-input shuffles should be canonicalized to be V1-input "
9166          "shuffles.");
9167
9168   // Try to use shift instructions.
9169   if (SDValue Shift =
9170           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9171     return Shift;
9172
9173   // See if we can use SSE4A Extraction / Insertion.
9174   if (Subtarget->hasSSE4A())
9175     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9176       return V;
9177
9178   // There are special ways we can lower some single-element blends.
9179   if (NumV2Inputs == 1)
9180     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9181                                                          Mask, Subtarget, DAG))
9182       return V;
9183
9184   // We have different paths for blend lowering, but they all must use the
9185   // *exact* same predicate.
9186   bool IsBlendSupported = Subtarget->hasSSE41();
9187   if (IsBlendSupported)
9188     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9189                                                   Subtarget, DAG))
9190       return Blend;
9191
9192   if (SDValue Masked =
9193           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9194     return Masked;
9195
9196   // Use dedicated unpack instructions for masks that match their pattern.
9197   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9198     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9199   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9200     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9201
9202   // Try to use byte rotation instructions.
9203   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9204           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9205     return Rotate;
9206
9207   if (SDValue BitBlend =
9208           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9209     return BitBlend;
9210
9211   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9212                                                             V2, Mask, DAG))
9213     return Unpack;
9214
9215   // If we can't directly blend but can use PSHUFB, that will be better as it
9216   // can both shuffle and set up the inefficient blend.
9217   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9218     bool V1InUse, V2InUse;
9219     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9220                                       V1InUse, V2InUse);
9221   }
9222
9223   // We can always bit-blend if we have to so the fallback strategy is to
9224   // decompose into single-input permutes and blends.
9225   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9226                                                       Mask, DAG);
9227 }
9228
9229 /// \brief Check whether a compaction lowering can be done by dropping even
9230 /// elements and compute how many times even elements must be dropped.
9231 ///
9232 /// This handles shuffles which take every Nth element where N is a power of
9233 /// two. Example shuffle masks:
9234 ///
9235 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9236 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9237 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9238 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9239 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9240 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9241 ///
9242 /// Any of these lanes can of course be undef.
9243 ///
9244 /// This routine only supports N <= 3.
9245 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9246 /// for larger N.
9247 ///
9248 /// \returns N above, or the number of times even elements must be dropped if
9249 /// there is such a number. Otherwise returns zero.
9250 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9251   // Figure out whether we're looping over two inputs or just one.
9252   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9253
9254   // The modulus for the shuffle vector entries is based on whether this is
9255   // a single input or not.
9256   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9257   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9258          "We should only be called with masks with a power-of-2 size!");
9259
9260   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9261
9262   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9263   // and 2^3 simultaneously. This is because we may have ambiguity with
9264   // partially undef inputs.
9265   bool ViableForN[3] = {true, true, true};
9266
9267   for (int i = 0, e = Mask.size(); i < e; ++i) {
9268     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9269     // want.
9270     if (Mask[i] == -1)
9271       continue;
9272
9273     bool IsAnyViable = false;
9274     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9275       if (ViableForN[j]) {
9276         uint64_t N = j + 1;
9277
9278         // The shuffle mask must be equal to (i * 2^N) % M.
9279         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9280           IsAnyViable = true;
9281         else
9282           ViableForN[j] = false;
9283       }
9284     // Early exit if we exhaust the possible powers of two.
9285     if (!IsAnyViable)
9286       break;
9287   }
9288
9289   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9290     if (ViableForN[j])
9291       return j + 1;
9292
9293   // Return 0 as there is no viable power of two.
9294   return 0;
9295 }
9296
9297 /// \brief Generic lowering of v16i8 shuffles.
9298 ///
9299 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9300 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9301 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9302 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9303 /// back together.
9304 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9305                                        const X86Subtarget *Subtarget,
9306                                        SelectionDAG &DAG) {
9307   SDLoc DL(Op);
9308   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9309   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9310   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9311   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9312   ArrayRef<int> Mask = SVOp->getMask();
9313   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9314
9315   // Try to use shift instructions.
9316   if (SDValue Shift =
9317           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9318     return Shift;
9319
9320   // Try to use byte rotation instructions.
9321   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9322           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9323     return Rotate;
9324
9325   // Try to use a zext lowering.
9326   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9327           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9328     return ZExt;
9329
9330   // See if we can use SSE4A Extraction / Insertion.
9331   if (Subtarget->hasSSE4A())
9332     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9333       return V;
9334
9335   int NumV2Elements =
9336       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9337
9338   // For single-input shuffles, there are some nicer lowering tricks we can use.
9339   if (NumV2Elements == 0) {
9340     // Check for being able to broadcast a single element.
9341     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9342                                                           Mask, Subtarget, DAG))
9343       return Broadcast;
9344
9345     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9346     // Notably, this handles splat and partial-splat shuffles more efficiently.
9347     // However, it only makes sense if the pre-duplication shuffle simplifies
9348     // things significantly. Currently, this means we need to be able to
9349     // express the pre-duplication shuffle as an i16 shuffle.
9350     //
9351     // FIXME: We should check for other patterns which can be widened into an
9352     // i16 shuffle as well.
9353     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9354       for (int i = 0; i < 16; i += 2)
9355         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9356           return false;
9357
9358       return true;
9359     };
9360     auto tryToWidenViaDuplication = [&]() -> SDValue {
9361       if (!canWidenViaDuplication(Mask))
9362         return SDValue();
9363       SmallVector<int, 4> LoInputs;
9364       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9365                    [](int M) { return M >= 0 && M < 8; });
9366       std::sort(LoInputs.begin(), LoInputs.end());
9367       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9368                      LoInputs.end());
9369       SmallVector<int, 4> HiInputs;
9370       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9371                    [](int M) { return M >= 8; });
9372       std::sort(HiInputs.begin(), HiInputs.end());
9373       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9374                      HiInputs.end());
9375
9376       bool TargetLo = LoInputs.size() >= HiInputs.size();
9377       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9378       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9379
9380       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9381       SmallDenseMap<int, int, 8> LaneMap;
9382       for (int I : InPlaceInputs) {
9383         PreDupI16Shuffle[I/2] = I/2;
9384         LaneMap[I] = I;
9385       }
9386       int j = TargetLo ? 0 : 4, je = j + 4;
9387       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9388         // Check if j is already a shuffle of this input. This happens when
9389         // there are two adjacent bytes after we move the low one.
9390         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9391           // If we haven't yet mapped the input, search for a slot into which
9392           // we can map it.
9393           while (j < je && PreDupI16Shuffle[j] != -1)
9394             ++j;
9395
9396           if (j == je)
9397             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9398             return SDValue();
9399
9400           // Map this input with the i16 shuffle.
9401           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9402         }
9403
9404         // Update the lane map based on the mapping we ended up with.
9405         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9406       }
9407       V1 = DAG.getBitcast(
9408           MVT::v16i8,
9409           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9410                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9411
9412       // Unpack the bytes to form the i16s that will be shuffled into place.
9413       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9414                        MVT::v16i8, V1, V1);
9415
9416       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9417       for (int i = 0; i < 16; ++i)
9418         if (Mask[i] != -1) {
9419           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9420           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9421           if (PostDupI16Shuffle[i / 2] == -1)
9422             PostDupI16Shuffle[i / 2] = MappedMask;
9423           else
9424             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9425                    "Conflicting entrties in the original shuffle!");
9426         }
9427       return DAG.getBitcast(
9428           MVT::v16i8,
9429           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9430                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9431     };
9432     if (SDValue V = tryToWidenViaDuplication())
9433       return V;
9434   }
9435
9436   if (SDValue Masked =
9437           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9438     return Masked;
9439
9440   // Use dedicated unpack instructions for masks that match their pattern.
9441   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9442                                          0, 16, 1, 17, 2, 18, 3, 19,
9443                                          // High half.
9444                                          4, 20, 5, 21, 6, 22, 7, 23}))
9445     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9446   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9447                                          8, 24, 9, 25, 10, 26, 11, 27,
9448                                          // High half.
9449                                          12, 28, 13, 29, 14, 30, 15, 31}))
9450     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9451
9452   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9453   // with PSHUFB. It is important to do this before we attempt to generate any
9454   // blends but after all of the single-input lowerings. If the single input
9455   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9456   // want to preserve that and we can DAG combine any longer sequences into
9457   // a PSHUFB in the end. But once we start blending from multiple inputs,
9458   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9459   // and there are *very* few patterns that would actually be faster than the
9460   // PSHUFB approach because of its ability to zero lanes.
9461   //
9462   // FIXME: The only exceptions to the above are blends which are exact
9463   // interleavings with direct instructions supporting them. We currently don't
9464   // handle those well here.
9465   if (Subtarget->hasSSSE3()) {
9466     bool V1InUse = false;
9467     bool V2InUse = false;
9468
9469     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9470                                                 DAG, V1InUse, V2InUse);
9471
9472     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9473     // do so. This avoids using them to handle blends-with-zero which is
9474     // important as a single pshufb is significantly faster for that.
9475     if (V1InUse && V2InUse) {
9476       if (Subtarget->hasSSE41())
9477         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9478                                                       Mask, Subtarget, DAG))
9479           return Blend;
9480
9481       // We can use an unpack to do the blending rather than an or in some
9482       // cases. Even though the or may be (very minorly) more efficient, we
9483       // preference this lowering because there are common cases where part of
9484       // the complexity of the shuffles goes away when we do the final blend as
9485       // an unpack.
9486       // FIXME: It might be worth trying to detect if the unpack-feeding
9487       // shuffles will both be pshufb, in which case we shouldn't bother with
9488       // this.
9489       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9490               DL, MVT::v16i8, V1, V2, Mask, DAG))
9491         return Unpack;
9492     }
9493
9494     return PSHUFB;
9495   }
9496
9497   // There are special ways we can lower some single-element blends.
9498   if (NumV2Elements == 1)
9499     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9500                                                          Mask, Subtarget, DAG))
9501       return V;
9502
9503   if (SDValue BitBlend =
9504           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9505     return BitBlend;
9506
9507   // Check whether a compaction lowering can be done. This handles shuffles
9508   // which take every Nth element for some even N. See the helper function for
9509   // details.
9510   //
9511   // We special case these as they can be particularly efficiently handled with
9512   // the PACKUSB instruction on x86 and they show up in common patterns of
9513   // rearranging bytes to truncate wide elements.
9514   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9515     // NumEvenDrops is the power of two stride of the elements. Another way of
9516     // thinking about it is that we need to drop the even elements this many
9517     // times to get the original input.
9518     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9519
9520     // First we need to zero all the dropped bytes.
9521     assert(NumEvenDrops <= 3 &&
9522            "No support for dropping even elements more than 3 times.");
9523     // We use the mask type to pick which bytes are preserved based on how many
9524     // elements are dropped.
9525     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9526     SDValue ByteClearMask = DAG.getBitcast(
9527         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9528     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9529     if (!IsSingleInput)
9530       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9531
9532     // Now pack things back together.
9533     V1 = DAG.getBitcast(MVT::v8i16, V1);
9534     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9535     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9536     for (int i = 1; i < NumEvenDrops; ++i) {
9537       Result = DAG.getBitcast(MVT::v8i16, Result);
9538       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9539     }
9540
9541     return Result;
9542   }
9543
9544   // Handle multi-input cases by blending single-input shuffles.
9545   if (NumV2Elements > 0)
9546     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9547                                                       Mask, DAG);
9548
9549   // The fallback path for single-input shuffles widens this into two v8i16
9550   // vectors with unpacks, shuffles those, and then pulls them back together
9551   // with a pack.
9552   SDValue V = V1;
9553
9554   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9555   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9556   for (int i = 0; i < 16; ++i)
9557     if (Mask[i] >= 0)
9558       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9559
9560   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9561
9562   SDValue VLoHalf, VHiHalf;
9563   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9564   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9565   // i16s.
9566   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9567                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9568       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9569                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9570     // Use a mask to drop the high bytes.
9571     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9572     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9573                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9574
9575     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9576     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9577
9578     // Squash the masks to point directly into VLoHalf.
9579     for (int &M : LoBlendMask)
9580       if (M >= 0)
9581         M /= 2;
9582     for (int &M : HiBlendMask)
9583       if (M >= 0)
9584         M /= 2;
9585   } else {
9586     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9587     // VHiHalf so that we can blend them as i16s.
9588     VLoHalf = DAG.getBitcast(
9589         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9590     VHiHalf = DAG.getBitcast(
9591         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9592   }
9593
9594   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9595   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9596
9597   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9598 }
9599
9600 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9601 ///
9602 /// This routine breaks down the specific type of 128-bit shuffle and
9603 /// dispatches to the lowering routines accordingly.
9604 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9605                                         MVT VT, const X86Subtarget *Subtarget,
9606                                         SelectionDAG &DAG) {
9607   switch (VT.SimpleTy) {
9608   case MVT::v2i64:
9609     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9610   case MVT::v2f64:
9611     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9612   case MVT::v4i32:
9613     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9614   case MVT::v4f32:
9615     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9616   case MVT::v8i16:
9617     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9618   case MVT::v16i8:
9619     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9620
9621   default:
9622     llvm_unreachable("Unimplemented!");
9623   }
9624 }
9625
9626 /// \brief Helper function to test whether a shuffle mask could be
9627 /// simplified by widening the elements being shuffled.
9628 ///
9629 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9630 /// leaves it in an unspecified state.
9631 ///
9632 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9633 /// shuffle masks. The latter have the special property of a '-2' representing
9634 /// a zero-ed lane of a vector.
9635 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9636                                     SmallVectorImpl<int> &WidenedMask) {
9637   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9638     // If both elements are undef, its trivial.
9639     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9640       WidenedMask.push_back(SM_SentinelUndef);
9641       continue;
9642     }
9643
9644     // Check for an undef mask and a mask value properly aligned to fit with
9645     // a pair of values. If we find such a case, use the non-undef mask's value.
9646     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9647       WidenedMask.push_back(Mask[i + 1] / 2);
9648       continue;
9649     }
9650     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9651       WidenedMask.push_back(Mask[i] / 2);
9652       continue;
9653     }
9654
9655     // When zeroing, we need to spread the zeroing across both lanes to widen.
9656     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9657       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9658           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9659         WidenedMask.push_back(SM_SentinelZero);
9660         continue;
9661       }
9662       return false;
9663     }
9664
9665     // Finally check if the two mask values are adjacent and aligned with
9666     // a pair.
9667     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9668       WidenedMask.push_back(Mask[i] / 2);
9669       continue;
9670     }
9671
9672     // Otherwise we can't safely widen the elements used in this shuffle.
9673     return false;
9674   }
9675   assert(WidenedMask.size() == Mask.size() / 2 &&
9676          "Incorrect size of mask after widening the elements!");
9677
9678   return true;
9679 }
9680
9681 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9682 ///
9683 /// This routine just extracts two subvectors, shuffles them independently, and
9684 /// then concatenates them back together. This should work effectively with all
9685 /// AVX vector shuffle types.
9686 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9687                                           SDValue V2, ArrayRef<int> Mask,
9688                                           SelectionDAG &DAG) {
9689   assert(VT.getSizeInBits() >= 256 &&
9690          "Only for 256-bit or wider vector shuffles!");
9691   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9692   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9693
9694   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9695   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9696
9697   int NumElements = VT.getVectorNumElements();
9698   int SplitNumElements = NumElements / 2;
9699   MVT ScalarVT = VT.getScalarType();
9700   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9701
9702   // Rather than splitting build-vectors, just build two narrower build
9703   // vectors. This helps shuffling with splats and zeros.
9704   auto SplitVector = [&](SDValue V) {
9705     while (V.getOpcode() == ISD::BITCAST)
9706       V = V->getOperand(0);
9707
9708     MVT OrigVT = V.getSimpleValueType();
9709     int OrigNumElements = OrigVT.getVectorNumElements();
9710     int OrigSplitNumElements = OrigNumElements / 2;
9711     MVT OrigScalarVT = OrigVT.getScalarType();
9712     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9713
9714     SDValue LoV, HiV;
9715
9716     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9717     if (!BV) {
9718       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9719                         DAG.getIntPtrConstant(0, DL));
9720       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9721                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9722     } else {
9723
9724       SmallVector<SDValue, 16> LoOps, HiOps;
9725       for (int i = 0; i < OrigSplitNumElements; ++i) {
9726         LoOps.push_back(BV->getOperand(i));
9727         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9728       }
9729       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9730       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9731     }
9732     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9733                           DAG.getBitcast(SplitVT, HiV));
9734   };
9735
9736   SDValue LoV1, HiV1, LoV2, HiV2;
9737   std::tie(LoV1, HiV1) = SplitVector(V1);
9738   std::tie(LoV2, HiV2) = SplitVector(V2);
9739
9740   // Now create two 4-way blends of these half-width vectors.
9741   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9742     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9743     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9744     for (int i = 0; i < SplitNumElements; ++i) {
9745       int M = HalfMask[i];
9746       if (M >= NumElements) {
9747         if (M >= NumElements + SplitNumElements)
9748           UseHiV2 = true;
9749         else
9750           UseLoV2 = true;
9751         V2BlendMask.push_back(M - NumElements);
9752         V1BlendMask.push_back(-1);
9753         BlendMask.push_back(SplitNumElements + i);
9754       } else if (M >= 0) {
9755         if (M >= SplitNumElements)
9756           UseHiV1 = true;
9757         else
9758           UseLoV1 = true;
9759         V2BlendMask.push_back(-1);
9760         V1BlendMask.push_back(M);
9761         BlendMask.push_back(i);
9762       } else {
9763         V2BlendMask.push_back(-1);
9764         V1BlendMask.push_back(-1);
9765         BlendMask.push_back(-1);
9766       }
9767     }
9768
9769     // Because the lowering happens after all combining takes place, we need to
9770     // manually combine these blend masks as much as possible so that we create
9771     // a minimal number of high-level vector shuffle nodes.
9772
9773     // First try just blending the halves of V1 or V2.
9774     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9775       return DAG.getUNDEF(SplitVT);
9776     if (!UseLoV2 && !UseHiV2)
9777       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9778     if (!UseLoV1 && !UseHiV1)
9779       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9780
9781     SDValue V1Blend, V2Blend;
9782     if (UseLoV1 && UseHiV1) {
9783       V1Blend =
9784         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9785     } else {
9786       // We only use half of V1 so map the usage down into the final blend mask.
9787       V1Blend = UseLoV1 ? LoV1 : HiV1;
9788       for (int i = 0; i < SplitNumElements; ++i)
9789         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9790           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9791     }
9792     if (UseLoV2 && UseHiV2) {
9793       V2Blend =
9794         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9795     } else {
9796       // We only use half of V2 so map the usage down into the final blend mask.
9797       V2Blend = UseLoV2 ? LoV2 : HiV2;
9798       for (int i = 0; i < SplitNumElements; ++i)
9799         if (BlendMask[i] >= SplitNumElements)
9800           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9801     }
9802     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9803   };
9804   SDValue Lo = HalfBlend(LoMask);
9805   SDValue Hi = HalfBlend(HiMask);
9806   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9807 }
9808
9809 /// \brief Either split a vector in halves or decompose the shuffles and the
9810 /// blend.
9811 ///
9812 /// This is provided as a good fallback for many lowerings of non-single-input
9813 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9814 /// between splitting the shuffle into 128-bit components and stitching those
9815 /// back together vs. extracting the single-input shuffles and blending those
9816 /// results.
9817 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9818                                                 SDValue V2, ArrayRef<int> Mask,
9819                                                 SelectionDAG &DAG) {
9820   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9821                                             "lower single-input shuffles as it "
9822                                             "could then recurse on itself.");
9823   int Size = Mask.size();
9824
9825   // If this can be modeled as a broadcast of two elements followed by a blend,
9826   // prefer that lowering. This is especially important because broadcasts can
9827   // often fold with memory operands.
9828   auto DoBothBroadcast = [&] {
9829     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9830     for (int M : Mask)
9831       if (M >= Size) {
9832         if (V2BroadcastIdx == -1)
9833           V2BroadcastIdx = M - Size;
9834         else if (M - Size != V2BroadcastIdx)
9835           return false;
9836       } else if (M >= 0) {
9837         if (V1BroadcastIdx == -1)
9838           V1BroadcastIdx = M;
9839         else if (M != V1BroadcastIdx)
9840           return false;
9841       }
9842     return true;
9843   };
9844   if (DoBothBroadcast())
9845     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9846                                                       DAG);
9847
9848   // If the inputs all stem from a single 128-bit lane of each input, then we
9849   // split them rather than blending because the split will decompose to
9850   // unusually few instructions.
9851   int LaneCount = VT.getSizeInBits() / 128;
9852   int LaneSize = Size / LaneCount;
9853   SmallBitVector LaneInputs[2];
9854   LaneInputs[0].resize(LaneCount, false);
9855   LaneInputs[1].resize(LaneCount, false);
9856   for (int i = 0; i < Size; ++i)
9857     if (Mask[i] >= 0)
9858       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9859   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9860     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9861
9862   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9863   // that the decomposed single-input shuffles don't end up here.
9864   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9865 }
9866
9867 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9868 /// a permutation and blend of those lanes.
9869 ///
9870 /// This essentially blends the out-of-lane inputs to each lane into the lane
9871 /// from a permuted copy of the vector. This lowering strategy results in four
9872 /// instructions in the worst case for a single-input cross lane shuffle which
9873 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9874 /// of. Special cases for each particular shuffle pattern should be handled
9875 /// prior to trying this lowering.
9876 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9877                                                        SDValue V1, SDValue V2,
9878                                                        ArrayRef<int> Mask,
9879                                                        SelectionDAG &DAG) {
9880   // FIXME: This should probably be generalized for 512-bit vectors as well.
9881   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9882   int LaneSize = Mask.size() / 2;
9883
9884   // If there are only inputs from one 128-bit lane, splitting will in fact be
9885   // less expensive. The flags track whether the given lane contains an element
9886   // that crosses to another lane.
9887   bool LaneCrossing[2] = {false, false};
9888   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9889     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9890       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9891   if (!LaneCrossing[0] || !LaneCrossing[1])
9892     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9893
9894   if (isSingleInputShuffleMask(Mask)) {
9895     SmallVector<int, 32> FlippedBlendMask;
9896     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9897       FlippedBlendMask.push_back(
9898           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9899                                   ? Mask[i]
9900                                   : Mask[i] % LaneSize +
9901                                         (i / LaneSize) * LaneSize + Size));
9902
9903     // Flip the vector, and blend the results which should now be in-lane. The
9904     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9905     // 5 for the high source. The value 3 selects the high half of source 2 and
9906     // the value 2 selects the low half of source 2. We only use source 2 to
9907     // allow folding it into a memory operand.
9908     unsigned PERMMask = 3 | 2 << 4;
9909     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9910                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9911     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9912   }
9913
9914   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9915   // will be handled by the above logic and a blend of the results, much like
9916   // other patterns in AVX.
9917   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9918 }
9919
9920 /// \brief Handle lowering 2-lane 128-bit shuffles.
9921 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9922                                         SDValue V2, ArrayRef<int> Mask,
9923                                         const X86Subtarget *Subtarget,
9924                                         SelectionDAG &DAG) {
9925   // TODO: If minimizing size and one of the inputs is a zero vector and the
9926   // the zero vector has only one use, we could use a VPERM2X128 to save the
9927   // instruction bytes needed to explicitly generate the zero vector.
9928
9929   // Blends are faster and handle all the non-lane-crossing cases.
9930   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9931                                                 Subtarget, DAG))
9932     return Blend;
9933
9934   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9935   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9936
9937   // If either input operand is a zero vector, use VPERM2X128 because its mask
9938   // allows us to replace the zero input with an implicit zero.
9939   if (!IsV1Zero && !IsV2Zero) {
9940     // Check for patterns which can be matched with a single insert of a 128-bit
9941     // subvector.
9942     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9943     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9944       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9945                                    VT.getVectorNumElements() / 2);
9946       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9947                                 DAG.getIntPtrConstant(0, DL));
9948       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9949                                 OnlyUsesV1 ? V1 : V2,
9950                                 DAG.getIntPtrConstant(0, DL));
9951       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9952     }
9953   }
9954
9955   // Otherwise form a 128-bit permutation. After accounting for undefs,
9956   // convert the 64-bit shuffle mask selection values into 128-bit
9957   // selection bits by dividing the indexes by 2 and shifting into positions
9958   // defined by a vperm2*128 instruction's immediate control byte.
9959
9960   // The immediate permute control byte looks like this:
9961   //    [1:0] - select 128 bits from sources for low half of destination
9962   //    [2]   - ignore
9963   //    [3]   - zero low half of destination
9964   //    [5:4] - select 128 bits from sources for high half of destination
9965   //    [6]   - ignore
9966   //    [7]   - zero high half of destination
9967
9968   int MaskLO = Mask[0];
9969   if (MaskLO == SM_SentinelUndef)
9970     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9971
9972   int MaskHI = Mask[2];
9973   if (MaskHI == SM_SentinelUndef)
9974     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9975
9976   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9977
9978   // If either input is a zero vector, replace it with an undef input.
9979   // Shuffle mask values <  4 are selecting elements of V1.
9980   // Shuffle mask values >= 4 are selecting elements of V2.
9981   // Adjust each half of the permute mask by clearing the half that was
9982   // selecting the zero vector and setting the zero mask bit.
9983   if (IsV1Zero) {
9984     V1 = DAG.getUNDEF(VT);
9985     if (MaskLO < 4)
9986       PermMask = (PermMask & 0xf0) | 0x08;
9987     if (MaskHI < 4)
9988       PermMask = (PermMask & 0x0f) | 0x80;
9989   }
9990   if (IsV2Zero) {
9991     V2 = DAG.getUNDEF(VT);
9992     if (MaskLO >= 4)
9993       PermMask = (PermMask & 0xf0) | 0x08;
9994     if (MaskHI >= 4)
9995       PermMask = (PermMask & 0x0f) | 0x80;
9996   }
9997
9998   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9999                      DAG.getConstant(PermMask, DL, MVT::i8));
10000 }
10001
10002 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10003 /// shuffling each lane.
10004 ///
10005 /// This will only succeed when the result of fixing the 128-bit lanes results
10006 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10007 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10008 /// the lane crosses early and then use simpler shuffles within each lane.
10009 ///
10010 /// FIXME: It might be worthwhile at some point to support this without
10011 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10012 /// in x86 only floating point has interesting non-repeating shuffles, and even
10013 /// those are still *marginally* more expensive.
10014 static SDValue lowerVectorShuffleByMerging128BitLanes(
10015     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10016     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10017   assert(!isSingleInputShuffleMask(Mask) &&
10018          "This is only useful with multiple inputs.");
10019
10020   int Size = Mask.size();
10021   int LaneSize = 128 / VT.getScalarSizeInBits();
10022   int NumLanes = Size / LaneSize;
10023   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10024
10025   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10026   // check whether the in-128-bit lane shuffles share a repeating pattern.
10027   SmallVector<int, 4> Lanes;
10028   Lanes.resize(NumLanes, -1);
10029   SmallVector<int, 4> InLaneMask;
10030   InLaneMask.resize(LaneSize, -1);
10031   for (int i = 0; i < Size; ++i) {
10032     if (Mask[i] < 0)
10033       continue;
10034
10035     int j = i / LaneSize;
10036
10037     if (Lanes[j] < 0) {
10038       // First entry we've seen for this lane.
10039       Lanes[j] = Mask[i] / LaneSize;
10040     } else if (Lanes[j] != Mask[i] / LaneSize) {
10041       // This doesn't match the lane selected previously!
10042       return SDValue();
10043     }
10044
10045     // Check that within each lane we have a consistent shuffle mask.
10046     int k = i % LaneSize;
10047     if (InLaneMask[k] < 0) {
10048       InLaneMask[k] = Mask[i] % LaneSize;
10049     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10050       // This doesn't fit a repeating in-lane mask.
10051       return SDValue();
10052     }
10053   }
10054
10055   // First shuffle the lanes into place.
10056   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10057                                 VT.getSizeInBits() / 64);
10058   SmallVector<int, 8> LaneMask;
10059   LaneMask.resize(NumLanes * 2, -1);
10060   for (int i = 0; i < NumLanes; ++i)
10061     if (Lanes[i] >= 0) {
10062       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10063       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10064     }
10065
10066   V1 = DAG.getBitcast(LaneVT, V1);
10067   V2 = DAG.getBitcast(LaneVT, V2);
10068   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10069
10070   // Cast it back to the type we actually want.
10071   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10072
10073   // Now do a simple shuffle that isn't lane crossing.
10074   SmallVector<int, 8> NewMask;
10075   NewMask.resize(Size, -1);
10076   for (int i = 0; i < Size; ++i)
10077     if (Mask[i] >= 0)
10078       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10079   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10080          "Must not introduce lane crosses at this point!");
10081
10082   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10083 }
10084
10085 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10086 /// given mask.
10087 ///
10088 /// This returns true if the elements from a particular input are already in the
10089 /// slot required by the given mask and require no permutation.
10090 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10091   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10092   int Size = Mask.size();
10093   for (int i = 0; i < Size; ++i)
10094     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10095       return false;
10096
10097   return true;
10098 }
10099
10100 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10101                                             ArrayRef<int> Mask, SDValue V1,
10102                                             SDValue V2, SelectionDAG &DAG) {
10103
10104   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10105   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10106   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10107   int NumElts = VT.getVectorNumElements();
10108   bool ShufpdMask = true;
10109   bool CommutableMask = true;
10110   unsigned Immediate = 0;
10111   for (int i = 0; i < NumElts; ++i) {
10112     if (Mask[i] < 0)
10113       continue;
10114     int Val = (i & 6) + NumElts * (i & 1);
10115     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10116     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10117       ShufpdMask = false;
10118     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10119       CommutableMask = false;
10120     Immediate |= (Mask[i] % 2) << i;
10121   }
10122   if (ShufpdMask)
10123     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10124                        DAG.getConstant(Immediate, DL, MVT::i8));
10125   if (CommutableMask)
10126     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10127                        DAG.getConstant(Immediate, DL, MVT::i8));
10128   return SDValue();
10129 }
10130
10131 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10132 ///
10133 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10134 /// isn't available.
10135 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10136                                        const X86Subtarget *Subtarget,
10137                                        SelectionDAG &DAG) {
10138   SDLoc DL(Op);
10139   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10140   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10141   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10142   ArrayRef<int> Mask = SVOp->getMask();
10143   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10144
10145   SmallVector<int, 4> WidenedMask;
10146   if (canWidenShuffleElements(Mask, WidenedMask))
10147     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10148                                     DAG);
10149
10150   if (isSingleInputShuffleMask(Mask)) {
10151     // Check for being able to broadcast a single element.
10152     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10153                                                           Mask, Subtarget, DAG))
10154       return Broadcast;
10155
10156     // Use low duplicate instructions for masks that match their pattern.
10157     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10158       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10159
10160     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10161       // Non-half-crossing single input shuffles can be lowerid with an
10162       // interleaved permutation.
10163       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10164                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10165       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10166                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10167     }
10168
10169     // With AVX2 we have direct support for this permutation.
10170     if (Subtarget->hasAVX2())
10171       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10172                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10173
10174     // Otherwise, fall back.
10175     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10176                                                    DAG);
10177   }
10178
10179   // X86 has dedicated unpack instructions that can handle specific blend
10180   // operations: UNPCKH and UNPCKL.
10181   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10182     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10183   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10184     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10185   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10186     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10187   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10188     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10189
10190   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10191                                                 Subtarget, DAG))
10192     return Blend;
10193
10194   // Check if the blend happens to exactly fit that of SHUFPD.
10195   if (SDValue Op =
10196       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10197     return Op;
10198
10199   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10200   // shuffle. However, if we have AVX2 and either inputs are already in place,
10201   // we will be able to shuffle even across lanes the other input in a single
10202   // instruction so skip this pattern.
10203   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10204                                  isShuffleMaskInputInPlace(1, Mask))))
10205     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10206             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10207       return Result;
10208
10209   // If we have AVX2 then we always want to lower with a blend because an v4 we
10210   // can fully permute the elements.
10211   if (Subtarget->hasAVX2())
10212     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10213                                                       Mask, DAG);
10214
10215   // Otherwise fall back on generic lowering.
10216   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10217 }
10218
10219 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10220 ///
10221 /// This routine is only called when we have AVX2 and thus a reasonable
10222 /// instruction set for v4i64 shuffling..
10223 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10224                                        const X86Subtarget *Subtarget,
10225                                        SelectionDAG &DAG) {
10226   SDLoc DL(Op);
10227   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10228   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10229   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10230   ArrayRef<int> Mask = SVOp->getMask();
10231   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10232   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10233
10234   SmallVector<int, 4> WidenedMask;
10235   if (canWidenShuffleElements(Mask, WidenedMask))
10236     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10237                                     DAG);
10238
10239   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10240                                                 Subtarget, DAG))
10241     return Blend;
10242
10243   // Check for being able to broadcast a single element.
10244   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10245                                                         Mask, Subtarget, DAG))
10246     return Broadcast;
10247
10248   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10249   // use lower latency instructions that will operate on both 128-bit lanes.
10250   SmallVector<int, 2> RepeatedMask;
10251   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10252     if (isSingleInputShuffleMask(Mask)) {
10253       int PSHUFDMask[] = {-1, -1, -1, -1};
10254       for (int i = 0; i < 2; ++i)
10255         if (RepeatedMask[i] >= 0) {
10256           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10257           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10258         }
10259       return DAG.getBitcast(
10260           MVT::v4i64,
10261           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10262                       DAG.getBitcast(MVT::v8i32, V1),
10263                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10264     }
10265   }
10266
10267   // AVX2 provides a direct instruction for permuting a single input across
10268   // lanes.
10269   if (isSingleInputShuffleMask(Mask))
10270     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10271                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10272
10273   // Try to use shift instructions.
10274   if (SDValue Shift =
10275           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10276     return Shift;
10277
10278   // Use dedicated unpack instructions for masks that match their pattern.
10279   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10280     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10281   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10282     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10283   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10284     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10285   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10286     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10287
10288   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10289   // shuffle. However, if we have AVX2 and either inputs are already in place,
10290   // we will be able to shuffle even across lanes the other input in a single
10291   // instruction so skip this pattern.
10292   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10293                                  isShuffleMaskInputInPlace(1, Mask))))
10294     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10295             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10296       return Result;
10297
10298   // Otherwise fall back on generic blend lowering.
10299   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10300                                                     Mask, DAG);
10301 }
10302
10303 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10304 ///
10305 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10306 /// isn't available.
10307 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10308                                        const X86Subtarget *Subtarget,
10309                                        SelectionDAG &DAG) {
10310   SDLoc DL(Op);
10311   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10312   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10313   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10314   ArrayRef<int> Mask = SVOp->getMask();
10315   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10316
10317   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10318                                                 Subtarget, DAG))
10319     return Blend;
10320
10321   // Check for being able to broadcast a single element.
10322   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10323                                                         Mask, Subtarget, DAG))
10324     return Broadcast;
10325
10326   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10327   // options to efficiently lower the shuffle.
10328   SmallVector<int, 4> RepeatedMask;
10329   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10330     assert(RepeatedMask.size() == 4 &&
10331            "Repeated masks must be half the mask width!");
10332
10333     // Use even/odd duplicate instructions for masks that match their pattern.
10334     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10335       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10336     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10337       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10338
10339     if (isSingleInputShuffleMask(Mask))
10340       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10341                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10342
10343     // Use dedicated unpack instructions for masks that match their pattern.
10344     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10345       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10346     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10347       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10348     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10349       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10350     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10351       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10352
10353     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10354     // have already handled any direct blends. We also need to squash the
10355     // repeated mask into a simulated v4f32 mask.
10356     for (int i = 0; i < 4; ++i)
10357       if (RepeatedMask[i] >= 8)
10358         RepeatedMask[i] -= 4;
10359     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10360   }
10361
10362   // If we have a single input shuffle with different shuffle patterns in the
10363   // two 128-bit lanes use the variable mask to VPERMILPS.
10364   if (isSingleInputShuffleMask(Mask)) {
10365     SDValue VPermMask[8];
10366     for (int i = 0; i < 8; ++i)
10367       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10368                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10369     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10370       return DAG.getNode(
10371           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10372           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10373
10374     if (Subtarget->hasAVX2())
10375       return DAG.getNode(
10376           X86ISD::VPERMV, DL, MVT::v8f32,
10377           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10378                                                  MVT::v8i32, VPermMask)),
10379           V1);
10380
10381     // Otherwise, fall back.
10382     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10383                                                    DAG);
10384   }
10385
10386   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10387   // shuffle.
10388   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10389           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10390     return Result;
10391
10392   // If we have AVX2 then we always want to lower with a blend because at v8 we
10393   // can fully permute the elements.
10394   if (Subtarget->hasAVX2())
10395     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10396                                                       Mask, DAG);
10397
10398   // Otherwise fall back on generic lowering.
10399   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10400 }
10401
10402 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10403 ///
10404 /// This routine is only called when we have AVX2 and thus a reasonable
10405 /// instruction set for v8i32 shuffling..
10406 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10407                                        const X86Subtarget *Subtarget,
10408                                        SelectionDAG &DAG) {
10409   SDLoc DL(Op);
10410   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10411   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10412   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10413   ArrayRef<int> Mask = SVOp->getMask();
10414   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10415   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10416
10417   // Whenever we can lower this as a zext, that instruction is strictly faster
10418   // than any alternative. It also allows us to fold memory operands into the
10419   // shuffle in many cases.
10420   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10421                                                          Mask, Subtarget, DAG))
10422     return ZExt;
10423
10424   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10425                                                 Subtarget, DAG))
10426     return Blend;
10427
10428   // Check for being able to broadcast a single element.
10429   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10430                                                         Mask, Subtarget, DAG))
10431     return Broadcast;
10432
10433   // If the shuffle mask is repeated in each 128-bit lane we can use more
10434   // efficient instructions that mirror the shuffles across the two 128-bit
10435   // lanes.
10436   SmallVector<int, 4> RepeatedMask;
10437   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10438     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10439     if (isSingleInputShuffleMask(Mask))
10440       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10441                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10442
10443     // Use dedicated unpack instructions for masks that match their pattern.
10444     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10445       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10446     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10447       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10448     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10449       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10450     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10451       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10452   }
10453
10454   // Try to use shift instructions.
10455   if (SDValue Shift =
10456           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10457     return Shift;
10458
10459   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10460           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10461     return Rotate;
10462
10463   // If the shuffle patterns aren't repeated but it is a single input, directly
10464   // generate a cross-lane VPERMD instruction.
10465   if (isSingleInputShuffleMask(Mask)) {
10466     SDValue VPermMask[8];
10467     for (int i = 0; i < 8; ++i)
10468       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10469                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10470     return DAG.getNode(
10471         X86ISD::VPERMV, DL, MVT::v8i32,
10472         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10473   }
10474
10475   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10476   // shuffle.
10477   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10478           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10479     return Result;
10480
10481   // Otherwise fall back on generic blend lowering.
10482   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10483                                                     Mask, DAG);
10484 }
10485
10486 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10487 ///
10488 /// This routine is only called when we have AVX2 and thus a reasonable
10489 /// instruction set for v16i16 shuffling..
10490 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10491                                         const X86Subtarget *Subtarget,
10492                                         SelectionDAG &DAG) {
10493   SDLoc DL(Op);
10494   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10495   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10496   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10497   ArrayRef<int> Mask = SVOp->getMask();
10498   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10499   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10500
10501   // Whenever we can lower this as a zext, that instruction is strictly faster
10502   // than any alternative. It also allows us to fold memory operands into the
10503   // shuffle in many cases.
10504   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10505                                                          Mask, Subtarget, DAG))
10506     return ZExt;
10507
10508   // Check for being able to broadcast a single element.
10509   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10510                                                         Mask, Subtarget, DAG))
10511     return Broadcast;
10512
10513   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10514                                                 Subtarget, DAG))
10515     return Blend;
10516
10517   // Use dedicated unpack instructions for masks that match their pattern.
10518   if (isShuffleEquivalent(V1, V2, Mask,
10519                           {// First 128-bit lane:
10520                            0, 16, 1, 17, 2, 18, 3, 19,
10521                            // Second 128-bit lane:
10522                            8, 24, 9, 25, 10, 26, 11, 27}))
10523     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10524   if (isShuffleEquivalent(V1, V2, Mask,
10525                           {// First 128-bit lane:
10526                            4, 20, 5, 21, 6, 22, 7, 23,
10527                            // Second 128-bit lane:
10528                            12, 28, 13, 29, 14, 30, 15, 31}))
10529     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10530
10531   // Try to use shift instructions.
10532   if (SDValue Shift =
10533           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10534     return Shift;
10535
10536   // Try to use byte rotation instructions.
10537   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10538           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10539     return Rotate;
10540
10541   if (isSingleInputShuffleMask(Mask)) {
10542     // There are no generalized cross-lane shuffle operations available on i16
10543     // element types.
10544     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10545       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10546                                                      Mask, DAG);
10547
10548     SmallVector<int, 8> RepeatedMask;
10549     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10550       // As this is a single-input shuffle, the repeated mask should be
10551       // a strictly valid v8i16 mask that we can pass through to the v8i16
10552       // lowering to handle even the v16 case.
10553       return lowerV8I16GeneralSingleInputVectorShuffle(
10554           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10555     }
10556
10557     SDValue PSHUFBMask[32];
10558     for (int i = 0; i < 16; ++i) {
10559       if (Mask[i] == -1) {
10560         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10561         continue;
10562       }
10563
10564       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10565       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10566       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10567       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10568     }
10569     return DAG.getBitcast(MVT::v16i16,
10570                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10571                                       DAG.getBitcast(MVT::v32i8, V1),
10572                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10573                                                   MVT::v32i8, PSHUFBMask)));
10574   }
10575
10576   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10577   // shuffle.
10578   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10579           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10580     return Result;
10581
10582   // Otherwise fall back on generic lowering.
10583   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10584 }
10585
10586 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10587 ///
10588 /// This routine is only called when we have AVX2 and thus a reasonable
10589 /// instruction set for v32i8 shuffling..
10590 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10591                                        const X86Subtarget *Subtarget,
10592                                        SelectionDAG &DAG) {
10593   SDLoc DL(Op);
10594   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10595   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10596   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10597   ArrayRef<int> Mask = SVOp->getMask();
10598   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10599   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10600
10601   // Whenever we can lower this as a zext, that instruction is strictly faster
10602   // than any alternative. It also allows us to fold memory operands into the
10603   // shuffle in many cases.
10604   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10605                                                          Mask, Subtarget, DAG))
10606     return ZExt;
10607
10608   // Check for being able to broadcast a single element.
10609   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10610                                                         Mask, Subtarget, DAG))
10611     return Broadcast;
10612
10613   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10614                                                 Subtarget, DAG))
10615     return Blend;
10616
10617   // Use dedicated unpack instructions for masks that match their pattern.
10618   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10619   // 256-bit lanes.
10620   if (isShuffleEquivalent(
10621           V1, V2, Mask,
10622           {// First 128-bit lane:
10623            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10624            // Second 128-bit lane:
10625            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10626     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10627   if (isShuffleEquivalent(
10628           V1, V2, Mask,
10629           {// First 128-bit lane:
10630            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10631            // Second 128-bit lane:
10632            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10633     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10634
10635   // Try to use shift instructions.
10636   if (SDValue Shift =
10637           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10638     return Shift;
10639
10640   // Try to use byte rotation instructions.
10641   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10642           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10643     return Rotate;
10644
10645   if (isSingleInputShuffleMask(Mask)) {
10646     // There are no generalized cross-lane shuffle operations available on i8
10647     // element types.
10648     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10649       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10650                                                      Mask, DAG);
10651
10652     SDValue PSHUFBMask[32];
10653     for (int i = 0; i < 32; ++i)
10654       PSHUFBMask[i] =
10655           Mask[i] < 0
10656               ? DAG.getUNDEF(MVT::i8)
10657               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10658                                 MVT::i8);
10659
10660     return DAG.getNode(
10661         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10662         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10663   }
10664
10665   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10666   // shuffle.
10667   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10668           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10669     return Result;
10670
10671   // Otherwise fall back on generic lowering.
10672   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10673 }
10674
10675 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10676 ///
10677 /// This routine either breaks down the specific type of a 256-bit x86 vector
10678 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10679 /// together based on the available instructions.
10680 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10681                                         MVT VT, const X86Subtarget *Subtarget,
10682                                         SelectionDAG &DAG) {
10683   SDLoc DL(Op);
10684   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10685   ArrayRef<int> Mask = SVOp->getMask();
10686
10687   // If we have a single input to the zero element, insert that into V1 if we
10688   // can do so cheaply.
10689   int NumElts = VT.getVectorNumElements();
10690   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10691     return M >= NumElts;
10692   });
10693
10694   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10695     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10696                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10697       return Insertion;
10698
10699   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10700   // can check for those subtargets here and avoid much of the subtarget
10701   // querying in the per-vector-type lowering routines. With AVX1 we have
10702   // essentially *zero* ability to manipulate a 256-bit vector with integer
10703   // types. Since we'll use floating point types there eventually, just
10704   // immediately cast everything to a float and operate entirely in that domain.
10705   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10706     int ElementBits = VT.getScalarSizeInBits();
10707     if (ElementBits < 32)
10708       // No floating point type available, decompose into 128-bit vectors.
10709       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10710
10711     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10712                                 VT.getVectorNumElements());
10713     V1 = DAG.getBitcast(FpVT, V1);
10714     V2 = DAG.getBitcast(FpVT, V2);
10715     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10716   }
10717
10718   switch (VT.SimpleTy) {
10719   case MVT::v4f64:
10720     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10721   case MVT::v4i64:
10722     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10723   case MVT::v8f32:
10724     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10725   case MVT::v8i32:
10726     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10727   case MVT::v16i16:
10728     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10729   case MVT::v32i8:
10730     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10731
10732   default:
10733     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10734   }
10735 }
10736
10737 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10738                                            ArrayRef<int> Mask, SDValue V1,
10739                                            SDValue V2, SelectionDAG &DAG) {
10740
10741   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10742
10743   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10744   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10745
10746   SmallVector<SDValue, 32>  VPermMask;
10747   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10748     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10749                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10750   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10751                                  VPermMask);
10752   if (isSingleInputShuffleMask(Mask))
10753     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10754
10755   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10756 }
10757
10758 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10759 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10760                                        const X86Subtarget *Subtarget,
10761                                        SelectionDAG &DAG) {
10762   SDLoc DL(Op);
10763   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10764   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10765   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10766   ArrayRef<int> Mask = SVOp->getMask();
10767   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10768
10769   if (SDValue Unpck =
10770           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10771     return Unpck;
10772
10773   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10774 }
10775
10776 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10777 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10778                                        const X86Subtarget *Subtarget,
10779                                        SelectionDAG &DAG) {
10780   SDLoc DL(Op);
10781   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10782   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10783   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10784   ArrayRef<int> Mask = SVOp->getMask();
10785   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10786
10787   if (SDValue Unpck =
10788           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10789     return Unpck;
10790
10791   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10792 }
10793
10794 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10795 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10796                                        const X86Subtarget *Subtarget,
10797                                        SelectionDAG &DAG) {
10798   SDLoc DL(Op);
10799   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10800   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10801   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10802   ArrayRef<int> Mask = SVOp->getMask();
10803   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10804
10805   if (SDValue Unpck =
10806           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10807     return Unpck;
10808
10809   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10810 }
10811
10812 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10813 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10814                                        const X86Subtarget *Subtarget,
10815                                        SelectionDAG &DAG) {
10816   SDLoc DL(Op);
10817   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10818   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10819   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10820   ArrayRef<int> Mask = SVOp->getMask();
10821   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10822
10823   if (SDValue Unpck =
10824           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10825     return Unpck;
10826
10827   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10828 }
10829
10830 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10831 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10832                                         const X86Subtarget *Subtarget,
10833                                         SelectionDAG &DAG) {
10834   SDLoc DL(Op);
10835   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10836   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10837   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10838   ArrayRef<int> Mask = SVOp->getMask();
10839   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10840   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10841
10842   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10843 }
10844
10845 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10846 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10847                                        const X86Subtarget *Subtarget,
10848                                        SelectionDAG &DAG) {
10849   SDLoc DL(Op);
10850   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10851   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10852   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10853   ArrayRef<int> Mask = SVOp->getMask();
10854   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10855   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10856
10857   // FIXME: Implement direct support for this type!
10858   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10859 }
10860
10861 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10862 ///
10863 /// This routine either breaks down the specific type of a 512-bit x86 vector
10864 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10865 /// together based on the available instructions.
10866 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10867                                         MVT VT, const X86Subtarget *Subtarget,
10868                                         SelectionDAG &DAG) {
10869   SDLoc DL(Op);
10870   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10871   ArrayRef<int> Mask = SVOp->getMask();
10872   assert(Subtarget->hasAVX512() &&
10873          "Cannot lower 512-bit vectors w/ basic ISA!");
10874
10875   // Check for being able to broadcast a single element.
10876   if (SDValue Broadcast =
10877           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10878     return Broadcast;
10879
10880   // Dispatch to each element type for lowering. If we don't have supprot for
10881   // specific element type shuffles at 512 bits, immediately split them and
10882   // lower them. Each lowering routine of a given type is allowed to assume that
10883   // the requisite ISA extensions for that element type are available.
10884   switch (VT.SimpleTy) {
10885   case MVT::v8f64:
10886     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10887   case MVT::v16f32:
10888     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10889   case MVT::v8i64:
10890     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10891   case MVT::v16i32:
10892     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10893   case MVT::v32i16:
10894     if (Subtarget->hasBWI())
10895       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10896     break;
10897   case MVT::v64i8:
10898     if (Subtarget->hasBWI())
10899       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10900     break;
10901
10902   default:
10903     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10904   }
10905
10906   // Otherwise fall back on splitting.
10907   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10908 }
10909
10910 // Lower vXi1 vector shuffles.
10911 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10912 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10913 // vector, shuffle and then truncate it back.
10914 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10915                                       MVT VT, const X86Subtarget *Subtarget,
10916                                       SelectionDAG &DAG) {
10917   SDLoc DL(Op);
10918   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10919   ArrayRef<int> Mask = SVOp->getMask();
10920   assert(Subtarget->hasAVX512() &&
10921          "Cannot lower 512-bit vectors w/o basic ISA!");
10922   EVT ExtVT;
10923   switch (VT.SimpleTy) {
10924   default:
10925     assert(false && "Expected a vector of i1 elements");
10926     break;
10927   case MVT::v2i1:
10928     ExtVT = MVT::v2i64;
10929     break;
10930   case MVT::v4i1:
10931     ExtVT = MVT::v4i32;
10932     break;
10933   case MVT::v8i1:
10934     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10935     break;
10936   case MVT::v16i1:
10937     ExtVT = MVT::v16i32;
10938     break;
10939   case MVT::v32i1:
10940     ExtVT = MVT::v32i16;
10941     break;
10942   case MVT::v64i1:
10943     ExtVT = MVT::v64i8;
10944     break;
10945   }
10946
10947   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10948     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10949   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10950     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10951   else
10952     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10953
10954   if (V2.isUndef())
10955     V2 = DAG.getUNDEF(ExtVT);
10956   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10957     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10958   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10959     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10960   else
10961     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10962   return DAG.getNode(ISD::TRUNCATE, DL, VT,
10963                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10964 }
10965 /// \brief Top-level lowering for x86 vector shuffles.
10966 ///
10967 /// This handles decomposition, canonicalization, and lowering of all x86
10968 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10969 /// above in helper routines. The canonicalization attempts to widen shuffles
10970 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10971 /// s.t. only one of the two inputs needs to be tested, etc.
10972 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10973                                   SelectionDAG &DAG) {
10974   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10975   ArrayRef<int> Mask = SVOp->getMask();
10976   SDValue V1 = Op.getOperand(0);
10977   SDValue V2 = Op.getOperand(1);
10978   MVT VT = Op.getSimpleValueType();
10979   int NumElements = VT.getVectorNumElements();
10980   SDLoc dl(Op);
10981   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10982
10983   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10984          "Can't lower MMX shuffles");
10985
10986   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10987   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10988   if (V1IsUndef && V2IsUndef)
10989     return DAG.getUNDEF(VT);
10990
10991   // When we create a shuffle node we put the UNDEF node to second operand,
10992   // but in some cases the first operand may be transformed to UNDEF.
10993   // In this case we should just commute the node.
10994   if (V1IsUndef)
10995     return DAG.getCommutedVectorShuffle(*SVOp);
10996
10997   // Check for non-undef masks pointing at an undef vector and make the masks
10998   // undef as well. This makes it easier to match the shuffle based solely on
10999   // the mask.
11000   if (V2IsUndef)
11001     for (int M : Mask)
11002       if (M >= NumElements) {
11003         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11004         for (int &M : NewMask)
11005           if (M >= NumElements)
11006             M = -1;
11007         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11008       }
11009
11010   // We actually see shuffles that are entirely re-arrangements of a set of
11011   // zero inputs. This mostly happens while decomposing complex shuffles into
11012   // simple ones. Directly lower these as a buildvector of zeros.
11013   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11014   if (Zeroable.all())
11015     return getZeroVector(VT, Subtarget, DAG, dl);
11016
11017   // Try to collapse shuffles into using a vector type with fewer elements but
11018   // wider element types. We cap this to not form integers or floating point
11019   // elements wider than 64 bits, but it might be interesting to form i128
11020   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11021   SmallVector<int, 16> WidenedMask;
11022   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11023       canWidenShuffleElements(Mask, WidenedMask)) {
11024     MVT NewEltVT = VT.isFloatingPoint()
11025                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11026                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11027     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11028     // Make sure that the new vector type is legal. For example, v2f64 isn't
11029     // legal on SSE1.
11030     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11031       V1 = DAG.getBitcast(NewVT, V1);
11032       V2 = DAG.getBitcast(NewVT, V2);
11033       return DAG.getBitcast(
11034           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11035     }
11036   }
11037
11038   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11039   for (int M : SVOp->getMask())
11040     if (M < 0)
11041       ++NumUndefElements;
11042     else if (M < NumElements)
11043       ++NumV1Elements;
11044     else
11045       ++NumV2Elements;
11046
11047   // Commute the shuffle as needed such that more elements come from V1 than
11048   // V2. This allows us to match the shuffle pattern strictly on how many
11049   // elements come from V1 without handling the symmetric cases.
11050   if (NumV2Elements > NumV1Elements)
11051     return DAG.getCommutedVectorShuffle(*SVOp);
11052
11053   // When the number of V1 and V2 elements are the same, try to minimize the
11054   // number of uses of V2 in the low half of the vector. When that is tied,
11055   // ensure that the sum of indices for V1 is equal to or lower than the sum
11056   // indices for V2. When those are equal, try to ensure that the number of odd
11057   // indices for V1 is lower than the number of odd indices for V2.
11058   if (NumV1Elements == NumV2Elements) {
11059     int LowV1Elements = 0, LowV2Elements = 0;
11060     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11061       if (M >= NumElements)
11062         ++LowV2Elements;
11063       else if (M >= 0)
11064         ++LowV1Elements;
11065     if (LowV2Elements > LowV1Elements) {
11066       return DAG.getCommutedVectorShuffle(*SVOp);
11067     } else if (LowV2Elements == LowV1Elements) {
11068       int SumV1Indices = 0, SumV2Indices = 0;
11069       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11070         if (SVOp->getMask()[i] >= NumElements)
11071           SumV2Indices += i;
11072         else if (SVOp->getMask()[i] >= 0)
11073           SumV1Indices += i;
11074       if (SumV2Indices < SumV1Indices) {
11075         return DAG.getCommutedVectorShuffle(*SVOp);
11076       } else if (SumV2Indices == SumV1Indices) {
11077         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11078         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11079           if (SVOp->getMask()[i] >= NumElements)
11080             NumV2OddIndices += i % 2;
11081           else if (SVOp->getMask()[i] >= 0)
11082             NumV1OddIndices += i % 2;
11083         if (NumV2OddIndices < NumV1OddIndices)
11084           return DAG.getCommutedVectorShuffle(*SVOp);
11085       }
11086     }
11087   }
11088
11089   // For each vector width, delegate to a specialized lowering routine.
11090   if (VT.getSizeInBits() == 128)
11091     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11092
11093   if (VT.getSizeInBits() == 256)
11094     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11095
11096   if (VT.getSizeInBits() == 512)
11097     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11098
11099   if (Is1BitVector)
11100     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11101   llvm_unreachable("Unimplemented!");
11102 }
11103
11104 // This function assumes its argument is a BUILD_VECTOR of constants or
11105 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11106 // true.
11107 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11108                                     unsigned &MaskValue) {
11109   MaskValue = 0;
11110   unsigned NumElems = BuildVector->getNumOperands();
11111   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11112   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11113   unsigned NumElemsInLane = NumElems / NumLanes;
11114
11115   // Blend for v16i16 should be symmetric for the both lanes.
11116   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11117     SDValue EltCond = BuildVector->getOperand(i);
11118     SDValue SndLaneEltCond =
11119         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11120
11121     int Lane1Cond = -1, Lane2Cond = -1;
11122     if (isa<ConstantSDNode>(EltCond))
11123       Lane1Cond = !isZero(EltCond);
11124     if (isa<ConstantSDNode>(SndLaneEltCond))
11125       Lane2Cond = !isZero(SndLaneEltCond);
11126
11127     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11128       // Lane1Cond != 0, means we want the first argument.
11129       // Lane1Cond == 0, means we want the second argument.
11130       // The encoding of this argument is 0 for the first argument, 1
11131       // for the second. Therefore, invert the condition.
11132       MaskValue |= !Lane1Cond << i;
11133     else if (Lane1Cond < 0)
11134       MaskValue |= !Lane2Cond << i;
11135     else
11136       return false;
11137   }
11138   return true;
11139 }
11140
11141 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11142 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11143                                            const X86Subtarget *Subtarget,
11144                                            SelectionDAG &DAG) {
11145   SDValue Cond = Op.getOperand(0);
11146   SDValue LHS = Op.getOperand(1);
11147   SDValue RHS = Op.getOperand(2);
11148   SDLoc dl(Op);
11149   MVT VT = Op.getSimpleValueType();
11150
11151   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11152     return SDValue();
11153   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11154
11155   // Only non-legal VSELECTs reach this lowering, convert those into generic
11156   // shuffles and re-use the shuffle lowering path for blends.
11157   SmallVector<int, 32> Mask;
11158   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11159     SDValue CondElt = CondBV->getOperand(i);
11160     Mask.push_back(
11161         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11162   }
11163   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11164 }
11165
11166 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11167   // A vselect where all conditions and data are constants can be optimized into
11168   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11169   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11170       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11171       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11172     return SDValue();
11173
11174   // Try to lower this to a blend-style vector shuffle. This can handle all
11175   // constant condition cases.
11176   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11177     return BlendOp;
11178
11179   // Variable blends are only legal from SSE4.1 onward.
11180   if (!Subtarget->hasSSE41())
11181     return SDValue();
11182
11183   // Only some types will be legal on some subtargets. If we can emit a legal
11184   // VSELECT-matching blend, return Op, and but if we need to expand, return
11185   // a null value.
11186   switch (Op.getSimpleValueType().SimpleTy) {
11187   default:
11188     // Most of the vector types have blends past SSE4.1.
11189     return Op;
11190
11191   case MVT::v32i8:
11192     // The byte blends for AVX vectors were introduced only in AVX2.
11193     if (Subtarget->hasAVX2())
11194       return Op;
11195
11196     return SDValue();
11197
11198   case MVT::v8i16:
11199   case MVT::v16i16:
11200     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11201     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11202       return Op;
11203
11204     // FIXME: We should custom lower this by fixing the condition and using i8
11205     // blends.
11206     return SDValue();
11207   }
11208 }
11209
11210 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11211   MVT VT = Op.getSimpleValueType();
11212   SDLoc dl(Op);
11213
11214   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11215     return SDValue();
11216
11217   if (VT.getSizeInBits() == 8) {
11218     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11219                                   Op.getOperand(0), Op.getOperand(1));
11220     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11221                                   DAG.getValueType(VT));
11222     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11223   }
11224
11225   if (VT.getSizeInBits() == 16) {
11226     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11227     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11228     if (Idx == 0)
11229       return DAG.getNode(
11230           ISD::TRUNCATE, dl, MVT::i16,
11231           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11232                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11233                       Op.getOperand(1)));
11234     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11235                                   Op.getOperand(0), Op.getOperand(1));
11236     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11237                                   DAG.getValueType(VT));
11238     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11239   }
11240
11241   if (VT == MVT::f32) {
11242     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11243     // the result back to FR32 register. It's only worth matching if the
11244     // result has a single use which is a store or a bitcast to i32.  And in
11245     // the case of a store, it's not worth it if the index is a constant 0,
11246     // because a MOVSSmr can be used instead, which is smaller and faster.
11247     if (!Op.hasOneUse())
11248       return SDValue();
11249     SDNode *User = *Op.getNode()->use_begin();
11250     if ((User->getOpcode() != ISD::STORE ||
11251          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11252           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11253         (User->getOpcode() != ISD::BITCAST ||
11254          User->getValueType(0) != MVT::i32))
11255       return SDValue();
11256     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11257                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11258                                   Op.getOperand(1));
11259     return DAG.getBitcast(MVT::f32, Extract);
11260   }
11261
11262   if (VT == MVT::i32 || VT == MVT::i64) {
11263     // ExtractPS/pextrq works with constant index.
11264     if (isa<ConstantSDNode>(Op.getOperand(1)))
11265       return Op;
11266   }
11267   return SDValue();
11268 }
11269
11270 /// Extract one bit from mask vector, like v16i1 or v8i1.
11271 /// AVX-512 feature.
11272 SDValue
11273 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11274   SDValue Vec = Op.getOperand(0);
11275   SDLoc dl(Vec);
11276   MVT VecVT = Vec.getSimpleValueType();
11277   SDValue Idx = Op.getOperand(1);
11278   MVT EltVT = Op.getSimpleValueType();
11279
11280   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11281   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11282          "Unexpected vector type in ExtractBitFromMaskVector");
11283
11284   // variable index can't be handled in mask registers,
11285   // extend vector to VR512
11286   if (!isa<ConstantSDNode>(Idx)) {
11287     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11288     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11289     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11290                               ExtVT.getVectorElementType(), Ext, Idx);
11291     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11292   }
11293
11294   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11295   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11296   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11297     rc = getRegClassFor(MVT::v16i1);
11298   unsigned MaxSift = rc->getSize()*8 - 1;
11299   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11300                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11301   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11302                     DAG.getConstant(MaxSift, dl, MVT::i8));
11303   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11304                        DAG.getIntPtrConstant(0, dl));
11305 }
11306
11307 SDValue
11308 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11309                                            SelectionDAG &DAG) const {
11310   SDLoc dl(Op);
11311   SDValue Vec = Op.getOperand(0);
11312   MVT VecVT = Vec.getSimpleValueType();
11313   SDValue Idx = Op.getOperand(1);
11314
11315   if (Op.getSimpleValueType() == MVT::i1)
11316     return ExtractBitFromMaskVector(Op, DAG);
11317
11318   if (!isa<ConstantSDNode>(Idx)) {
11319     if (VecVT.is512BitVector() ||
11320         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11321          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11322
11323       MVT MaskEltVT =
11324         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11325       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11326                                     MaskEltVT.getSizeInBits());
11327
11328       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11329       auto PtrVT = getPointerTy(DAG.getDataLayout());
11330       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11331                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11332                                  DAG.getConstant(0, dl, PtrVT));
11333       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11334       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11335                          DAG.getConstant(0, dl, PtrVT));
11336     }
11337     return SDValue();
11338   }
11339
11340   // If this is a 256-bit vector result, first extract the 128-bit vector and
11341   // then extract the element from the 128-bit vector.
11342   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11343
11344     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11345     // Get the 128-bit vector.
11346     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11347     MVT EltVT = VecVT.getVectorElementType();
11348
11349     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11350
11351     //if (IdxVal >= NumElems/2)
11352     //  IdxVal -= NumElems/2;
11353     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11354     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11355                        DAG.getConstant(IdxVal, dl, MVT::i32));
11356   }
11357
11358   assert(VecVT.is128BitVector() && "Unexpected vector length");
11359
11360   if (Subtarget->hasSSE41())
11361     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11362       return Res;
11363
11364   MVT VT = Op.getSimpleValueType();
11365   // TODO: handle v16i8.
11366   if (VT.getSizeInBits() == 16) {
11367     SDValue Vec = Op.getOperand(0);
11368     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11369     if (Idx == 0)
11370       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11371                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11372                                      DAG.getBitcast(MVT::v4i32, Vec),
11373                                      Op.getOperand(1)));
11374     // Transform it so it match pextrw which produces a 32-bit result.
11375     MVT EltVT = MVT::i32;
11376     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11377                                   Op.getOperand(0), Op.getOperand(1));
11378     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11379                                   DAG.getValueType(VT));
11380     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11381   }
11382
11383   if (VT.getSizeInBits() == 32) {
11384     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11385     if (Idx == 0)
11386       return Op;
11387
11388     // SHUFPS the element to the lowest double word, then movss.
11389     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11390     MVT VVT = Op.getOperand(0).getSimpleValueType();
11391     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11392                                        DAG.getUNDEF(VVT), Mask);
11393     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11394                        DAG.getIntPtrConstant(0, dl));
11395   }
11396
11397   if (VT.getSizeInBits() == 64) {
11398     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11399     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11400     //        to match extract_elt for f64.
11401     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11402     if (Idx == 0)
11403       return Op;
11404
11405     // UNPCKHPD the element to the lowest double word, then movsd.
11406     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11407     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11408     int Mask[2] = { 1, -1 };
11409     MVT VVT = Op.getOperand(0).getSimpleValueType();
11410     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11411                                        DAG.getUNDEF(VVT), Mask);
11412     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11413                        DAG.getIntPtrConstant(0, dl));
11414   }
11415
11416   return SDValue();
11417 }
11418
11419 /// Insert one bit to mask vector, like v16i1 or v8i1.
11420 /// AVX-512 feature.
11421 SDValue
11422 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11423   SDLoc dl(Op);
11424   SDValue Vec = Op.getOperand(0);
11425   SDValue Elt = Op.getOperand(1);
11426   SDValue Idx = Op.getOperand(2);
11427   MVT VecVT = Vec.getSimpleValueType();
11428
11429   if (!isa<ConstantSDNode>(Idx)) {
11430     // Non constant index. Extend source and destination,
11431     // insert element and then truncate the result.
11432     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11433     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11434     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11435       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11436       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11437     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11438   }
11439
11440   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11441   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11442   if (IdxVal)
11443     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11444                            DAG.getConstant(IdxVal, dl, MVT::i8));
11445   if (Vec.getOpcode() == ISD::UNDEF)
11446     return EltInVec;
11447   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11448 }
11449
11450 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11451                                                   SelectionDAG &DAG) const {
11452   MVT VT = Op.getSimpleValueType();
11453   MVT EltVT = VT.getVectorElementType();
11454
11455   if (EltVT == MVT::i1)
11456     return InsertBitToMaskVector(Op, DAG);
11457
11458   SDLoc dl(Op);
11459   SDValue N0 = Op.getOperand(0);
11460   SDValue N1 = Op.getOperand(1);
11461   SDValue N2 = Op.getOperand(2);
11462   if (!isa<ConstantSDNode>(N2))
11463     return SDValue();
11464   auto *N2C = cast<ConstantSDNode>(N2);
11465   unsigned IdxVal = N2C->getZExtValue();
11466
11467   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11468   // into that, and then insert the subvector back into the result.
11469   if (VT.is256BitVector() || VT.is512BitVector()) {
11470     // With a 256-bit vector, we can insert into the zero element efficiently
11471     // using a blend if we have AVX or AVX2 and the right data type.
11472     if (VT.is256BitVector() && IdxVal == 0) {
11473       // TODO: It is worthwhile to cast integer to floating point and back
11474       // and incur a domain crossing penalty if that's what we'll end up
11475       // doing anyway after extracting to a 128-bit vector.
11476       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11477           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11478         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11479         N2 = DAG.getIntPtrConstant(1, dl);
11480         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11481       }
11482     }
11483
11484     // Get the desired 128-bit vector chunk.
11485     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11486
11487     // Insert the element into the desired chunk.
11488     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11489     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11490
11491     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11492                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11493
11494     // Insert the changed part back into the bigger vector
11495     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11496   }
11497   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11498
11499   if (Subtarget->hasSSE41()) {
11500     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11501       unsigned Opc;
11502       if (VT == MVT::v8i16) {
11503         Opc = X86ISD::PINSRW;
11504       } else {
11505         assert(VT == MVT::v16i8);
11506         Opc = X86ISD::PINSRB;
11507       }
11508
11509       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11510       // argument.
11511       if (N1.getValueType() != MVT::i32)
11512         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11513       if (N2.getValueType() != MVT::i32)
11514         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11515       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11516     }
11517
11518     if (EltVT == MVT::f32) {
11519       // Bits [7:6] of the constant are the source select. This will always be
11520       //   zero here. The DAG Combiner may combine an extract_elt index into
11521       //   these bits. For example (insert (extract, 3), 2) could be matched by
11522       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11523       // Bits [5:4] of the constant are the destination select. This is the
11524       //   value of the incoming immediate.
11525       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11526       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11527
11528       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11529       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11530         // If this is an insertion of 32-bits into the low 32-bits of
11531         // a vector, we prefer to generate a blend with immediate rather
11532         // than an insertps. Blends are simpler operations in hardware and so
11533         // will always have equal or better performance than insertps.
11534         // But if optimizing for size and there's a load folding opportunity,
11535         // generate insertps because blendps does not have a 32-bit memory
11536         // operand form.
11537         N2 = DAG.getIntPtrConstant(1, dl);
11538         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11539         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11540       }
11541       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11542       // Create this as a scalar to vector..
11543       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11544       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11545     }
11546
11547     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11548       // PINSR* works with constant index.
11549       return Op;
11550     }
11551   }
11552
11553   if (EltVT == MVT::i8)
11554     return SDValue();
11555
11556   if (EltVT.getSizeInBits() == 16) {
11557     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11558     // as its second argument.
11559     if (N1.getValueType() != MVT::i32)
11560       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11561     if (N2.getValueType() != MVT::i32)
11562       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11563     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11564   }
11565   return SDValue();
11566 }
11567
11568 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11569   SDLoc dl(Op);
11570   MVT OpVT = Op.getSimpleValueType();
11571
11572   // If this is a 256-bit vector result, first insert into a 128-bit
11573   // vector and then insert into the 256-bit vector.
11574   if (!OpVT.is128BitVector()) {
11575     // Insert into a 128-bit vector.
11576     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11577     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11578                                  OpVT.getVectorNumElements() / SizeFactor);
11579
11580     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11581
11582     // Insert the 128-bit vector.
11583     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11584   }
11585
11586   if (OpVT == MVT::v1i64 &&
11587       Op.getOperand(0).getValueType() == MVT::i64)
11588     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11589
11590   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11591   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11592   return DAG.getBitcast(
11593       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11594 }
11595
11596 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11597 // a simple subregister reference or explicit instructions to grab
11598 // upper bits of a vector.
11599 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11600                                       SelectionDAG &DAG) {
11601   SDLoc dl(Op);
11602   SDValue In =  Op.getOperand(0);
11603   SDValue Idx = Op.getOperand(1);
11604   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11605   MVT ResVT   = Op.getSimpleValueType();
11606   MVT InVT    = In.getSimpleValueType();
11607
11608   if (Subtarget->hasFp256()) {
11609     if (ResVT.is128BitVector() &&
11610         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11611         isa<ConstantSDNode>(Idx)) {
11612       return Extract128BitVector(In, IdxVal, DAG, dl);
11613     }
11614     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11615         isa<ConstantSDNode>(Idx)) {
11616       return Extract256BitVector(In, IdxVal, DAG, dl);
11617     }
11618   }
11619   return SDValue();
11620 }
11621
11622 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11623 // simple superregister reference or explicit instructions to insert
11624 // the upper bits of a vector.
11625 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11626                                      SelectionDAG &DAG) {
11627   if (!Subtarget->hasAVX())
11628     return SDValue();
11629
11630   SDLoc dl(Op);
11631   SDValue Vec = Op.getOperand(0);
11632   SDValue SubVec = Op.getOperand(1);
11633   SDValue Idx = Op.getOperand(2);
11634
11635   if (!isa<ConstantSDNode>(Idx))
11636     return SDValue();
11637
11638   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11639   MVT OpVT = Op.getSimpleValueType();
11640   MVT SubVecVT = SubVec.getSimpleValueType();
11641
11642   // Fold two 16-byte subvector loads into one 32-byte load:
11643   // (insert_subvector (insert_subvector undef, (load addr), 0),
11644   //                   (load addr + 16), Elts/2)
11645   // --> load32 addr
11646   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11647       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11648       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11649     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11650     if (Idx2 && Idx2->getZExtValue() == 0) {
11651       SDValue SubVec2 = Vec.getOperand(1);
11652       // If needed, look through a bitcast to get to the load.
11653       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11654         SubVec2 = SubVec2.getOperand(0);
11655
11656       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11657         bool Fast;
11658         unsigned Alignment = FirstLd->getAlignment();
11659         unsigned AS = FirstLd->getAddressSpace();
11660         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11661         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11662                                     OpVT, AS, Alignment, &Fast) && Fast) {
11663           SDValue Ops[] = { SubVec2, SubVec };
11664           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11665             return Ld;
11666         }
11667       }
11668     }
11669   }
11670
11671   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11672       SubVecVT.is128BitVector())
11673     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11674
11675   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11676     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11677
11678   if (OpVT.getVectorElementType() == MVT::i1) {
11679     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11680       return Op;
11681     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11682     SDValue Undef = DAG.getUNDEF(OpVT);
11683     unsigned NumElems = OpVT.getVectorNumElements();
11684     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11685
11686     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11687       // Zero upper bits of the Vec
11688       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11689       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11690
11691       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11692                                  SubVec, ZeroIdx);
11693       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11694       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11695     }
11696     if (IdxVal == 0) {
11697       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11698                                  SubVec, ZeroIdx);
11699       // Zero upper bits of the Vec2
11700       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11701       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11702       // Zero lower bits of the Vec
11703       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11704       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11705       // Merge them together
11706       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11707     }
11708   }
11709   return SDValue();
11710 }
11711
11712 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11713 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11714 // one of the above mentioned nodes. It has to be wrapped because otherwise
11715 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11716 // be used to form addressing mode. These wrapped nodes will be selected
11717 // into MOV32ri.
11718 SDValue
11719 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11720   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11721
11722   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11723   // global base reg.
11724   unsigned char OpFlag = 0;
11725   unsigned WrapperKind = X86ISD::Wrapper;
11726   CodeModel::Model M = DAG.getTarget().getCodeModel();
11727
11728   if (Subtarget->isPICStyleRIPRel() &&
11729       (M == CodeModel::Small || M == CodeModel::Kernel))
11730     WrapperKind = X86ISD::WrapperRIP;
11731   else if (Subtarget->isPICStyleGOT())
11732     OpFlag = X86II::MO_GOTOFF;
11733   else if (Subtarget->isPICStyleStubPIC())
11734     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11735
11736   auto PtrVT = getPointerTy(DAG.getDataLayout());
11737   SDValue Result = DAG.getTargetConstantPool(
11738       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11739   SDLoc DL(CP);
11740   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11741   // With PIC, the address is actually $g + Offset.
11742   if (OpFlag) {
11743     Result =
11744         DAG.getNode(ISD::ADD, DL, PtrVT,
11745                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11746   }
11747
11748   return Result;
11749 }
11750
11751 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11752   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11753
11754   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11755   // global base reg.
11756   unsigned char OpFlag = 0;
11757   unsigned WrapperKind = X86ISD::Wrapper;
11758   CodeModel::Model M = DAG.getTarget().getCodeModel();
11759
11760   if (Subtarget->isPICStyleRIPRel() &&
11761       (M == CodeModel::Small || M == CodeModel::Kernel))
11762     WrapperKind = X86ISD::WrapperRIP;
11763   else if (Subtarget->isPICStyleGOT())
11764     OpFlag = X86II::MO_GOTOFF;
11765   else if (Subtarget->isPICStyleStubPIC())
11766     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11767
11768   auto PtrVT = getPointerTy(DAG.getDataLayout());
11769   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11770   SDLoc DL(JT);
11771   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11772
11773   // With PIC, the address is actually $g + Offset.
11774   if (OpFlag)
11775     Result =
11776         DAG.getNode(ISD::ADD, DL, PtrVT,
11777                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11778
11779   return Result;
11780 }
11781
11782 SDValue
11783 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11784   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11785
11786   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11787   // global base reg.
11788   unsigned char OpFlag = 0;
11789   unsigned WrapperKind = X86ISD::Wrapper;
11790   CodeModel::Model M = DAG.getTarget().getCodeModel();
11791
11792   if (Subtarget->isPICStyleRIPRel() &&
11793       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11794     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11795       OpFlag = X86II::MO_GOTPCREL;
11796     WrapperKind = X86ISD::WrapperRIP;
11797   } else if (Subtarget->isPICStyleGOT()) {
11798     OpFlag = X86II::MO_GOT;
11799   } else if (Subtarget->isPICStyleStubPIC()) {
11800     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11801   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11802     OpFlag = X86II::MO_DARWIN_NONLAZY;
11803   }
11804
11805   auto PtrVT = getPointerTy(DAG.getDataLayout());
11806   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11807
11808   SDLoc DL(Op);
11809   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11810
11811   // With PIC, the address is actually $g + Offset.
11812   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11813       !Subtarget->is64Bit()) {
11814     Result =
11815         DAG.getNode(ISD::ADD, DL, PtrVT,
11816                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11817   }
11818
11819   // For symbols that require a load from a stub to get the address, emit the
11820   // load.
11821   if (isGlobalStubReference(OpFlag))
11822     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11823                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11824                          false, false, false, 0);
11825
11826   return Result;
11827 }
11828
11829 SDValue
11830 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11831   // Create the TargetBlockAddressAddress node.
11832   unsigned char OpFlags =
11833     Subtarget->ClassifyBlockAddressReference();
11834   CodeModel::Model M = DAG.getTarget().getCodeModel();
11835   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11836   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11837   SDLoc dl(Op);
11838   auto PtrVT = getPointerTy(DAG.getDataLayout());
11839   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11840
11841   if (Subtarget->isPICStyleRIPRel() &&
11842       (M == CodeModel::Small || M == CodeModel::Kernel))
11843     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11844   else
11845     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11846
11847   // With PIC, the address is actually $g + Offset.
11848   if (isGlobalRelativeToPICBase(OpFlags)) {
11849     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11850                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11851   }
11852
11853   return Result;
11854 }
11855
11856 SDValue
11857 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11858                                       int64_t Offset, SelectionDAG &DAG) const {
11859   // Create the TargetGlobalAddress node, folding in the constant
11860   // offset if it is legal.
11861   unsigned char OpFlags =
11862       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11863   CodeModel::Model M = DAG.getTarget().getCodeModel();
11864   auto PtrVT = getPointerTy(DAG.getDataLayout());
11865   SDValue Result;
11866   if (OpFlags == X86II::MO_NO_FLAG &&
11867       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11868     // A direct static reference to a global.
11869     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11870     Offset = 0;
11871   } else {
11872     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11873   }
11874
11875   if (Subtarget->isPICStyleRIPRel() &&
11876       (M == CodeModel::Small || M == CodeModel::Kernel))
11877     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11878   else
11879     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11880
11881   // With PIC, the address is actually $g + Offset.
11882   if (isGlobalRelativeToPICBase(OpFlags)) {
11883     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11884                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11885   }
11886
11887   // For globals that require a load from a stub to get the address, emit the
11888   // load.
11889   if (isGlobalStubReference(OpFlags))
11890     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11891                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11892                          false, false, false, 0);
11893
11894   // If there was a non-zero offset that we didn't fold, create an explicit
11895   // addition for it.
11896   if (Offset != 0)
11897     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11898                          DAG.getConstant(Offset, dl, PtrVT));
11899
11900   return Result;
11901 }
11902
11903 SDValue
11904 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11905   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11906   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11907   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11908 }
11909
11910 static SDValue
11911 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11912            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11913            unsigned char OperandFlags, bool LocalDynamic = false) {
11914   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11915   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11916   SDLoc dl(GA);
11917   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11918                                            GA->getValueType(0),
11919                                            GA->getOffset(),
11920                                            OperandFlags);
11921
11922   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11923                                            : X86ISD::TLSADDR;
11924
11925   if (InFlag) {
11926     SDValue Ops[] = { Chain,  TGA, *InFlag };
11927     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11928   } else {
11929     SDValue Ops[]  = { Chain, TGA };
11930     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11931   }
11932
11933   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11934   MFI->setAdjustsStack(true);
11935   MFI->setHasCalls(true);
11936
11937   SDValue Flag = Chain.getValue(1);
11938   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11939 }
11940
11941 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11942 static SDValue
11943 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11944                                 const EVT PtrVT) {
11945   SDValue InFlag;
11946   SDLoc dl(GA);  // ? function entry point might be better
11947   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11948                                    DAG.getNode(X86ISD::GlobalBaseReg,
11949                                                SDLoc(), PtrVT), InFlag);
11950   InFlag = Chain.getValue(1);
11951
11952   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11953 }
11954
11955 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11956 static SDValue
11957 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11958                                 const EVT PtrVT) {
11959   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11960                     X86::RAX, X86II::MO_TLSGD);
11961 }
11962
11963 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11964                                            SelectionDAG &DAG,
11965                                            const EVT PtrVT,
11966                                            bool is64Bit) {
11967   SDLoc dl(GA);
11968
11969   // Get the start address of the TLS block for this module.
11970   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11971       .getInfo<X86MachineFunctionInfo>();
11972   MFI->incNumLocalDynamicTLSAccesses();
11973
11974   SDValue Base;
11975   if (is64Bit) {
11976     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11977                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11978   } else {
11979     SDValue InFlag;
11980     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11981         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11982     InFlag = Chain.getValue(1);
11983     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11984                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11985   }
11986
11987   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11988   // of Base.
11989
11990   // Build x@dtpoff.
11991   unsigned char OperandFlags = X86II::MO_DTPOFF;
11992   unsigned WrapperKind = X86ISD::Wrapper;
11993   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11994                                            GA->getValueType(0),
11995                                            GA->getOffset(), OperandFlags);
11996   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11997
11998   // Add x@dtpoff with the base.
11999   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12000 }
12001
12002 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12003 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12004                                    const EVT PtrVT, TLSModel::Model model,
12005                                    bool is64Bit, bool isPIC) {
12006   SDLoc dl(GA);
12007
12008   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12009   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12010                                                          is64Bit ? 257 : 256));
12011
12012   SDValue ThreadPointer =
12013       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12014                   MachinePointerInfo(Ptr), false, false, false, 0);
12015
12016   unsigned char OperandFlags = 0;
12017   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12018   // initialexec.
12019   unsigned WrapperKind = X86ISD::Wrapper;
12020   if (model == TLSModel::LocalExec) {
12021     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12022   } else if (model == TLSModel::InitialExec) {
12023     if (is64Bit) {
12024       OperandFlags = X86II::MO_GOTTPOFF;
12025       WrapperKind = X86ISD::WrapperRIP;
12026     } else {
12027       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12028     }
12029   } else {
12030     llvm_unreachable("Unexpected model");
12031   }
12032
12033   // emit "addl x@ntpoff,%eax" (local exec)
12034   // or "addl x@indntpoff,%eax" (initial exec)
12035   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12036   SDValue TGA =
12037       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12038                                  GA->getOffset(), OperandFlags);
12039   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12040
12041   if (model == TLSModel::InitialExec) {
12042     if (isPIC && !is64Bit) {
12043       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12044                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12045                            Offset);
12046     }
12047
12048     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12049                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12050                          false, false, false, 0);
12051   }
12052
12053   // The address of the thread local variable is the add of the thread
12054   // pointer with the offset of the variable.
12055   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12056 }
12057
12058 SDValue
12059 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12060
12061   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12062   const GlobalValue *GV = GA->getGlobal();
12063   auto PtrVT = getPointerTy(DAG.getDataLayout());
12064
12065   if (Subtarget->isTargetELF()) {
12066     if (DAG.getTarget().Options.EmulatedTLS)
12067       return LowerToTLSEmulatedModel(GA, DAG);
12068     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12069     switch (model) {
12070       case TLSModel::GeneralDynamic:
12071         if (Subtarget->is64Bit())
12072           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12073         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12074       case TLSModel::LocalDynamic:
12075         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12076                                            Subtarget->is64Bit());
12077       case TLSModel::InitialExec:
12078       case TLSModel::LocalExec:
12079         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12080                                    DAG.getTarget().getRelocationModel() ==
12081                                        Reloc::PIC_);
12082     }
12083     llvm_unreachable("Unknown TLS model.");
12084   }
12085
12086   if (Subtarget->isTargetDarwin()) {
12087     // Darwin only has one model of TLS.  Lower to that.
12088     unsigned char OpFlag = 0;
12089     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12090                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12091
12092     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12093     // global base reg.
12094     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12095                  !Subtarget->is64Bit();
12096     if (PIC32)
12097       OpFlag = X86II::MO_TLVP_PIC_BASE;
12098     else
12099       OpFlag = X86II::MO_TLVP;
12100     SDLoc DL(Op);
12101     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12102                                                 GA->getValueType(0),
12103                                                 GA->getOffset(), OpFlag);
12104     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12105
12106     // With PIC32, the address is actually $g + Offset.
12107     if (PIC32)
12108       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12109                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12110                            Offset);
12111
12112     // Lowering the machine isd will make sure everything is in the right
12113     // location.
12114     SDValue Chain = DAG.getEntryNode();
12115     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12116     SDValue Args[] = { Chain, Offset };
12117     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12118
12119     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12120     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12121     MFI->setAdjustsStack(true);
12122
12123     // And our return value (tls address) is in the standard call return value
12124     // location.
12125     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12126     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12127   }
12128
12129   if (Subtarget->isTargetKnownWindowsMSVC() ||
12130       Subtarget->isTargetWindowsGNU()) {
12131     // Just use the implicit TLS architecture
12132     // Need to generate someting similar to:
12133     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12134     //                                  ; from TEB
12135     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12136     //   mov     rcx, qword [rdx+rcx*8]
12137     //   mov     eax, .tls$:tlsvar
12138     //   [rax+rcx] contains the address
12139     // Windows 64bit: gs:0x58
12140     // Windows 32bit: fs:__tls_array
12141
12142     SDLoc dl(GA);
12143     SDValue Chain = DAG.getEntryNode();
12144
12145     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12146     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12147     // use its literal value of 0x2C.
12148     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12149                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12150                                                              256)
12151                                         : Type::getInt32PtrTy(*DAG.getContext(),
12152                                                               257));
12153
12154     SDValue TlsArray = Subtarget->is64Bit()
12155                            ? DAG.getIntPtrConstant(0x58, dl)
12156                            : (Subtarget->isTargetWindowsGNU()
12157                                   ? DAG.getIntPtrConstant(0x2C, dl)
12158                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12159
12160     SDValue ThreadPointer =
12161         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12162                     false, false, 0);
12163
12164     SDValue res;
12165     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12166       res = ThreadPointer;
12167     } else {
12168       // Load the _tls_index variable
12169       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12170       if (Subtarget->is64Bit())
12171         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12172                              MachinePointerInfo(), MVT::i32, false, false,
12173                              false, 0);
12174       else
12175         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12176                           false, false, 0);
12177
12178       auto &DL = DAG.getDataLayout();
12179       SDValue Scale =
12180           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12181       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12182
12183       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12184     }
12185
12186     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12187                       false, 0);
12188
12189     // Get the offset of start of .tls section
12190     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12191                                              GA->getValueType(0),
12192                                              GA->getOffset(), X86II::MO_SECREL);
12193     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12194
12195     // The address of the thread local variable is the add of the thread
12196     // pointer with the offset of the variable.
12197     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12198   }
12199
12200   llvm_unreachable("TLS not implemented for this target.");
12201 }
12202
12203 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12204 /// and take a 2 x i32 value to shift plus a shift amount.
12205 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12206   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12207   MVT VT = Op.getSimpleValueType();
12208   unsigned VTBits = VT.getSizeInBits();
12209   SDLoc dl(Op);
12210   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12211   SDValue ShOpLo = Op.getOperand(0);
12212   SDValue ShOpHi = Op.getOperand(1);
12213   SDValue ShAmt  = Op.getOperand(2);
12214   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12215   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12216   // during isel.
12217   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12218                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12219   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12220                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12221                        : DAG.getConstant(0, dl, VT);
12222
12223   SDValue Tmp2, Tmp3;
12224   if (Op.getOpcode() == ISD::SHL_PARTS) {
12225     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12226     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12227   } else {
12228     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12229     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12230   }
12231
12232   // If the shift amount is larger or equal than the width of a part we can't
12233   // rely on the results of shld/shrd. Insert a test and select the appropriate
12234   // values for large shift amounts.
12235   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12236                                 DAG.getConstant(VTBits, dl, MVT::i8));
12237   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12238                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12239
12240   SDValue Hi, Lo;
12241   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12242   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12243   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12244
12245   if (Op.getOpcode() == ISD::SHL_PARTS) {
12246     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12247     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12248   } else {
12249     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12250     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12251   }
12252
12253   SDValue Ops[2] = { Lo, Hi };
12254   return DAG.getMergeValues(Ops, dl);
12255 }
12256
12257 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12258                                            SelectionDAG &DAG) const {
12259   SDValue Src = Op.getOperand(0);
12260   MVT SrcVT = Src.getSimpleValueType();
12261   MVT VT = Op.getSimpleValueType();
12262   SDLoc dl(Op);
12263
12264   if (SrcVT.isVector()) {
12265     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12266       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12267                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12268                          DAG.getUNDEF(SrcVT)));
12269     }
12270     if (SrcVT.getVectorElementType() == MVT::i1) {
12271       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12272       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12273                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12274     }
12275     return SDValue();
12276   }
12277
12278   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12279          "Unknown SINT_TO_FP to lower!");
12280
12281   // These are really Legal; return the operand so the caller accepts it as
12282   // Legal.
12283   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12284     return Op;
12285   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12286       Subtarget->is64Bit()) {
12287     return Op;
12288   }
12289
12290   unsigned Size = SrcVT.getSizeInBits()/8;
12291   MachineFunction &MF = DAG.getMachineFunction();
12292   auto PtrVT = getPointerTy(MF.getDataLayout());
12293   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12294   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12295   SDValue Chain = DAG.getStore(
12296       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12297       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12298       false, 0);
12299   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12300 }
12301
12302 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12303                                      SDValue StackSlot,
12304                                      SelectionDAG &DAG) const {
12305   // Build the FILD
12306   SDLoc DL(Op);
12307   SDVTList Tys;
12308   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12309   if (useSSE)
12310     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12311   else
12312     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12313
12314   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12315
12316   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12317   MachineMemOperand *MMO;
12318   if (FI) {
12319     int SSFI = FI->getIndex();
12320     MMO = DAG.getMachineFunction().getMachineMemOperand(
12321         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12322         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12323   } else {
12324     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12325     StackSlot = StackSlot.getOperand(1);
12326   }
12327   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12328   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12329                                            X86ISD::FILD, DL,
12330                                            Tys, Ops, SrcVT, MMO);
12331
12332   if (useSSE) {
12333     Chain = Result.getValue(1);
12334     SDValue InFlag = Result.getValue(2);
12335
12336     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12337     // shouldn't be necessary except that RFP cannot be live across
12338     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12339     MachineFunction &MF = DAG.getMachineFunction();
12340     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12341     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12342     auto PtrVT = getPointerTy(MF.getDataLayout());
12343     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12344     Tys = DAG.getVTList(MVT::Other);
12345     SDValue Ops[] = {
12346       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12347     };
12348     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12349         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12350         MachineMemOperand::MOStore, SSFISize, SSFISize);
12351
12352     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12353                                     Ops, Op.getValueType(), MMO);
12354     Result = DAG.getLoad(
12355         Op.getValueType(), DL, Chain, StackSlot,
12356         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12357         false, false, false, 0);
12358   }
12359
12360   return Result;
12361 }
12362
12363 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12364 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12365                                                SelectionDAG &DAG) const {
12366   // This algorithm is not obvious. Here it is what we're trying to output:
12367   /*
12368      movq       %rax,  %xmm0
12369      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12370      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12371      #ifdef __SSE3__
12372        haddpd   %xmm0, %xmm0
12373      #else
12374        pshufd   $0x4e, %xmm0, %xmm1
12375        addpd    %xmm1, %xmm0
12376      #endif
12377   */
12378
12379   SDLoc dl(Op);
12380   LLVMContext *Context = DAG.getContext();
12381
12382   // Build some magic constants.
12383   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12384   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12385   auto PtrVT = getPointerTy(DAG.getDataLayout());
12386   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12387
12388   SmallVector<Constant*,2> CV1;
12389   CV1.push_back(
12390     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12391                                       APInt(64, 0x4330000000000000ULL))));
12392   CV1.push_back(
12393     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12394                                       APInt(64, 0x4530000000000000ULL))));
12395   Constant *C1 = ConstantVector::get(CV1);
12396   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12397
12398   // Load the 64-bit value into an XMM register.
12399   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12400                             Op.getOperand(0));
12401   SDValue CLod0 =
12402       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12403                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12404                   false, false, false, 16);
12405   SDValue Unpck1 =
12406       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12407
12408   SDValue CLod1 =
12409       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12410                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12411                   false, false, false, 16);
12412   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12413   // TODO: Are there any fast-math-flags to propagate here?
12414   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12415   SDValue Result;
12416
12417   if (Subtarget->hasSSE3()) {
12418     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12419     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12420   } else {
12421     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12422     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12423                                            S2F, 0x4E, DAG);
12424     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12425                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12426   }
12427
12428   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12429                      DAG.getIntPtrConstant(0, dl));
12430 }
12431
12432 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12433 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12434                                                SelectionDAG &DAG) const {
12435   SDLoc dl(Op);
12436   // FP constant to bias correct the final result.
12437   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12438                                    MVT::f64);
12439
12440   // Load the 32-bit value into an XMM register.
12441   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12442                              Op.getOperand(0));
12443
12444   // Zero out the upper parts of the register.
12445   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12446
12447   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12448                      DAG.getBitcast(MVT::v2f64, Load),
12449                      DAG.getIntPtrConstant(0, dl));
12450
12451   // Or the load with the bias.
12452   SDValue Or = DAG.getNode(
12453       ISD::OR, dl, MVT::v2i64,
12454       DAG.getBitcast(MVT::v2i64,
12455                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12456       DAG.getBitcast(MVT::v2i64,
12457                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12458   Or =
12459       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12460                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12461
12462   // Subtract the bias.
12463   // TODO: Are there any fast-math-flags to propagate here?
12464   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12465
12466   // Handle final rounding.
12467   EVT DestVT = Op.getValueType();
12468
12469   if (DestVT.bitsLT(MVT::f64))
12470     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12471                        DAG.getIntPtrConstant(0, dl));
12472   if (DestVT.bitsGT(MVT::f64))
12473     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12474
12475   // Handle final rounding.
12476   return Sub;
12477 }
12478
12479 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12480                                      const X86Subtarget &Subtarget) {
12481   // The algorithm is the following:
12482   // #ifdef __SSE4_1__
12483   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12484   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12485   //                                 (uint4) 0x53000000, 0xaa);
12486   // #else
12487   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12488   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12489   // #endif
12490   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12491   //     return (float4) lo + fhi;
12492
12493   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12494   // reassociate the two FADDs, and if we do that, the algorithm fails
12495   // spectacularly (PR24512).
12496   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12497   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12498   // there's also the MachineCombiner reassociations happening on Machine IR.
12499   if (DAG.getTarget().Options.UnsafeFPMath)
12500     return SDValue();
12501
12502   SDLoc DL(Op);
12503   SDValue V = Op->getOperand(0);
12504   EVT VecIntVT = V.getValueType();
12505   bool Is128 = VecIntVT == MVT::v4i32;
12506   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12507   // If we convert to something else than the supported type, e.g., to v4f64,
12508   // abort early.
12509   if (VecFloatVT != Op->getValueType(0))
12510     return SDValue();
12511
12512   unsigned NumElts = VecIntVT.getVectorNumElements();
12513   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12514          "Unsupported custom type");
12515   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12516
12517   // In the #idef/#else code, we have in common:
12518   // - The vector of constants:
12519   // -- 0x4b000000
12520   // -- 0x53000000
12521   // - A shift:
12522   // -- v >> 16
12523
12524   // Create the splat vector for 0x4b000000.
12525   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12526   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12527                            CstLow, CstLow, CstLow, CstLow};
12528   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12529                                   makeArrayRef(&CstLowArray[0], NumElts));
12530   // Create the splat vector for 0x53000000.
12531   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12532   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12533                             CstHigh, CstHigh, CstHigh, CstHigh};
12534   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12535                                    makeArrayRef(&CstHighArray[0], NumElts));
12536
12537   // Create the right shift.
12538   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12539   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12540                              CstShift, CstShift, CstShift, CstShift};
12541   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12542                                     makeArrayRef(&CstShiftArray[0], NumElts));
12543   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12544
12545   SDValue Low, High;
12546   if (Subtarget.hasSSE41()) {
12547     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12548     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12549     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12550     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12551     // Low will be bitcasted right away, so do not bother bitcasting back to its
12552     // original type.
12553     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12554                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12555     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12556     //                                 (uint4) 0x53000000, 0xaa);
12557     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12558     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12559     // High will be bitcasted right away, so do not bother bitcasting back to
12560     // its original type.
12561     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12562                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12563   } else {
12564     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12565     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12566                                      CstMask, CstMask, CstMask);
12567     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12568     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12569     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12570
12571     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12572     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12573   }
12574
12575   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12576   SDValue CstFAdd = DAG.getConstantFP(
12577       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12578   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12579                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12580   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12581                                    makeArrayRef(&CstFAddArray[0], NumElts));
12582
12583   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12584   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12585   // TODO: Are there any fast-math-flags to propagate here?
12586   SDValue FHigh =
12587       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12588   //     return (float4) lo + fhi;
12589   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12590   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12591 }
12592
12593 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12594                                                SelectionDAG &DAG) const {
12595   SDValue N0 = Op.getOperand(0);
12596   MVT SVT = N0.getSimpleValueType();
12597   SDLoc dl(Op);
12598
12599   switch (SVT.SimpleTy) {
12600   default:
12601     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12602   case MVT::v4i8:
12603   case MVT::v4i16:
12604   case MVT::v8i8:
12605   case MVT::v8i16: {
12606     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12607     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12608                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12609   }
12610   case MVT::v4i32:
12611   case MVT::v8i32:
12612     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12613   case MVT::v16i8:
12614   case MVT::v16i16:
12615     if (Subtarget->hasAVX512())
12616       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12617                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12618   }
12619   llvm_unreachable(nullptr);
12620 }
12621
12622 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12623                                            SelectionDAG &DAG) const {
12624   SDValue N0 = Op.getOperand(0);
12625   SDLoc dl(Op);
12626   auto PtrVT = getPointerTy(DAG.getDataLayout());
12627
12628   if (Op.getValueType().isVector())
12629     return lowerUINT_TO_FP_vec(Op, DAG);
12630
12631   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12632   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12633   // the optimization here.
12634   if (DAG.SignBitIsZero(N0))
12635     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12636
12637   MVT SrcVT = N0.getSimpleValueType();
12638   MVT DstVT = Op.getSimpleValueType();
12639
12640   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12641       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12642     // Conversions from unsigned i32 to f32/f64 are legal,
12643     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12644     return Op;
12645   }
12646
12647   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12648     return LowerUINT_TO_FP_i64(Op, DAG);
12649   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12650     return LowerUINT_TO_FP_i32(Op, DAG);
12651   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12652     return SDValue();
12653
12654   // Make a 64-bit buffer, and use it to build an FILD.
12655   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12656   if (SrcVT == MVT::i32) {
12657     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12658     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12659     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12660                                   StackSlot, MachinePointerInfo(),
12661                                   false, false, 0);
12662     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12663                                   OffsetSlot, MachinePointerInfo(),
12664                                   false, false, 0);
12665     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12666     return Fild;
12667   }
12668
12669   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12670   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12671                                StackSlot, MachinePointerInfo(),
12672                                false, false, 0);
12673   // For i64 source, we need to add the appropriate power of 2 if the input
12674   // was negative.  This is the same as the optimization in
12675   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12676   // we must be careful to do the computation in x87 extended precision, not
12677   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12678   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12679   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12680       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12681       MachineMemOperand::MOLoad, 8, 8);
12682
12683   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12684   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12685   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12686                                          MVT::i64, MMO);
12687
12688   APInt FF(32, 0x5F800000ULL);
12689
12690   // Check whether the sign bit is set.
12691   SDValue SignSet = DAG.getSetCC(
12692       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12693       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12694
12695   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12696   SDValue FudgePtr = DAG.getConstantPool(
12697       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12698
12699   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12700   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12701   SDValue Four = DAG.getIntPtrConstant(4, dl);
12702   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12703                                Zero, Four);
12704   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12705
12706   // Load the value out, extending it from f32 to f80.
12707   // FIXME: Avoid the extend by constructing the right constant pool?
12708   SDValue Fudge = DAG.getExtLoad(
12709       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12710       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12711       false, false, false, 4);
12712   // Extend everything to 80 bits to force it to be done on x87.
12713   // TODO: Are there any fast-math-flags to propagate here?
12714   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12715   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12716                      DAG.getIntPtrConstant(0, dl));
12717 }
12718
12719 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12720 // is legal, or has an f16 source (which needs to be promoted to f32),
12721 // just return an <SDValue(), SDValue()> pair.
12722 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12723 // to i16, i32 or i64, and we lower it to a legal sequence.
12724 // If lowered to the final integer result we return a <result, SDValue()> pair.
12725 // Otherwise we lower it to a sequence ending with a FIST, return a
12726 // <FIST, StackSlot> pair, and the caller is responsible for loading
12727 // the final integer result from StackSlot.
12728 std::pair<SDValue,SDValue>
12729 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12730                                    bool IsSigned, bool IsReplace) const {
12731   SDLoc DL(Op);
12732
12733   EVT DstTy = Op.getValueType();
12734   EVT TheVT = Op.getOperand(0).getValueType();
12735   auto PtrVT = getPointerTy(DAG.getDataLayout());
12736
12737   if (TheVT == MVT::f16)
12738     // We need to promote the f16 to f32 before using the lowering
12739     // in this routine.
12740     return std::make_pair(SDValue(), SDValue());
12741
12742   assert((TheVT == MVT::f32 ||
12743           TheVT == MVT::f64 ||
12744           TheVT == MVT::f80) &&
12745          "Unexpected FP operand type in FP_TO_INTHelper");
12746
12747   // If using FIST to compute an unsigned i64, we'll need some fixup
12748   // to handle values above the maximum signed i64.  A FIST is always
12749   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12750   bool UnsignedFixup = !IsSigned &&
12751                        DstTy == MVT::i64 &&
12752                        (!Subtarget->is64Bit() ||
12753                         !isScalarFPTypeInSSEReg(TheVT));
12754
12755   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12756     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12757     // The low 32 bits of the fist result will have the correct uint32 result.
12758     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12759     DstTy = MVT::i64;
12760   }
12761
12762   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12763          DstTy.getSimpleVT() >= MVT::i16 &&
12764          "Unknown FP_TO_INT to lower!");
12765
12766   // These are really Legal.
12767   if (DstTy == MVT::i32 &&
12768       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12769     return std::make_pair(SDValue(), SDValue());
12770   if (Subtarget->is64Bit() &&
12771       DstTy == MVT::i64 &&
12772       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12773     return std::make_pair(SDValue(), SDValue());
12774
12775   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12776   // stack slot.
12777   MachineFunction &MF = DAG.getMachineFunction();
12778   unsigned MemSize = DstTy.getSizeInBits()/8;
12779   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12780   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12781
12782   unsigned Opc;
12783   switch (DstTy.getSimpleVT().SimpleTy) {
12784   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12785   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12786   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12787   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12788   }
12789
12790   SDValue Chain = DAG.getEntryNode();
12791   SDValue Value = Op.getOperand(0);
12792   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12793
12794   if (UnsignedFixup) {
12795     //
12796     // Conversion to unsigned i64 is implemented with a select,
12797     // depending on whether the source value fits in the range
12798     // of a signed i64.  Let Thresh be the FP equivalent of
12799     // 0x8000000000000000ULL.
12800     //
12801     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12802     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12803     //  Fist-to-mem64 FistSrc
12804     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12805     //  to XOR'ing the high 32 bits with Adjust.
12806     //
12807     // Being a power of 2, Thresh is exactly representable in all FP formats.
12808     // For X87 we'd like to use the smallest FP type for this constant, but
12809     // for DAG type consistency we have to match the FP operand type.
12810
12811     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12812     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12813     bool LosesInfo = false;
12814     if (TheVT == MVT::f64)
12815       // The rounding mode is irrelevant as the conversion should be exact.
12816       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12817                               &LosesInfo);
12818     else if (TheVT == MVT::f80)
12819       Status = Thresh.convert(APFloat::x87DoubleExtended,
12820                               APFloat::rmNearestTiesToEven, &LosesInfo);
12821
12822     assert(Status == APFloat::opOK && !LosesInfo &&
12823            "FP conversion should have been exact");
12824
12825     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12826
12827     SDValue Cmp = DAG.getSetCC(DL,
12828                                getSetCCResultType(DAG.getDataLayout(),
12829                                                   *DAG.getContext(), TheVT),
12830                                Value, ThreshVal, ISD::SETLT);
12831     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12832                            DAG.getConstant(0, DL, MVT::i32),
12833                            DAG.getConstant(0x80000000, DL, MVT::i32));
12834     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12835     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12836                                               *DAG.getContext(), TheVT),
12837                        Value, ThreshVal, ISD::SETLT);
12838     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12839   }
12840
12841   // FIXME This causes a redundant load/store if the SSE-class value is already
12842   // in memory, such as if it is on the callstack.
12843   if (isScalarFPTypeInSSEReg(TheVT)) {
12844     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12845     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12846                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12847                          false, 0);
12848     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12849     SDValue Ops[] = {
12850       Chain, StackSlot, DAG.getValueType(TheVT)
12851     };
12852
12853     MachineMemOperand *MMO =
12854         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12855                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12856     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12857     Chain = Value.getValue(1);
12858     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12859     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12860   }
12861
12862   MachineMemOperand *MMO =
12863       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12864                               MachineMemOperand::MOStore, MemSize, MemSize);
12865
12866   if (UnsignedFixup) {
12867
12868     // Insert the FIST, load its result as two i32's,
12869     // and XOR the high i32 with Adjust.
12870
12871     SDValue FistOps[] = { Chain, Value, StackSlot };
12872     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12873                                            FistOps, DstTy, MMO);
12874
12875     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12876                                 MachinePointerInfo(),
12877                                 false, false, false, 0);
12878     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12879                                    DAG.getConstant(4, DL, PtrVT));
12880
12881     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12882                                  MachinePointerInfo(),
12883                                  false, false, false, 0);
12884     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12885
12886     if (Subtarget->is64Bit()) {
12887       // Join High32 and Low32 into a 64-bit result.
12888       // (High32 << 32) | Low32
12889       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12890       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12891       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12892                            DAG.getConstant(32, DL, MVT::i8));
12893       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12894       return std::make_pair(Result, SDValue());
12895     }
12896
12897     SDValue ResultOps[] = { Low32, High32 };
12898
12899     SDValue pair = IsReplace
12900       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12901       : DAG.getMergeValues(ResultOps, DL);
12902     return std::make_pair(pair, SDValue());
12903   } else {
12904     // Build the FP_TO_INT*_IN_MEM
12905     SDValue Ops[] = { Chain, Value, StackSlot };
12906     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12907                                            Ops, DstTy, MMO);
12908     return std::make_pair(FIST, StackSlot);
12909   }
12910 }
12911
12912 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12913                               const X86Subtarget *Subtarget) {
12914   MVT VT = Op->getSimpleValueType(0);
12915   SDValue In = Op->getOperand(0);
12916   MVT InVT = In.getSimpleValueType();
12917   SDLoc dl(Op);
12918
12919   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12920     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12921
12922   // Optimize vectors in AVX mode:
12923   //
12924   //   v8i16 -> v8i32
12925   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12926   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12927   //   Concat upper and lower parts.
12928   //
12929   //   v4i32 -> v4i64
12930   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12931   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12932   //   Concat upper and lower parts.
12933   //
12934
12935   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12936       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12937       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12938     return SDValue();
12939
12940   if (Subtarget->hasInt256())
12941     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12942
12943   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12944   SDValue Undef = DAG.getUNDEF(InVT);
12945   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12946   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12947   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12948
12949   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12950                              VT.getVectorNumElements()/2);
12951
12952   OpLo = DAG.getBitcast(HVT, OpLo);
12953   OpHi = DAG.getBitcast(HVT, OpHi);
12954
12955   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12956 }
12957
12958 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12959                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12960   MVT VT = Op->getSimpleValueType(0);
12961   SDValue In = Op->getOperand(0);
12962   MVT InVT = In.getSimpleValueType();
12963   SDLoc DL(Op);
12964   unsigned int NumElts = VT.getVectorNumElements();
12965   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12966     return SDValue();
12967
12968   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12969     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12970
12971   assert(InVT.getVectorElementType() == MVT::i1);
12972   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12973   SDValue One =
12974    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12975   SDValue Zero =
12976    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12977
12978   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12979   if (VT.is512BitVector())
12980     return V;
12981   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12982 }
12983
12984 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12985                                SelectionDAG &DAG) {
12986   if (Subtarget->hasFp256())
12987     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12988       return Res;
12989
12990   return SDValue();
12991 }
12992
12993 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12994                                 SelectionDAG &DAG) {
12995   SDLoc DL(Op);
12996   MVT VT = Op.getSimpleValueType();
12997   SDValue In = Op.getOperand(0);
12998   MVT SVT = In.getSimpleValueType();
12999
13000   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13001     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13002
13003   if (Subtarget->hasFp256())
13004     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13005       return Res;
13006
13007   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13008          VT.getVectorNumElements() != SVT.getVectorNumElements());
13009   return SDValue();
13010 }
13011
13012 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13013   SDLoc DL(Op);
13014   MVT VT = Op.getSimpleValueType();
13015   SDValue In = Op.getOperand(0);
13016   MVT InVT = In.getSimpleValueType();
13017
13018   if (VT == MVT::i1) {
13019     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13020            "Invalid scalar TRUNCATE operation");
13021     if (InVT.getSizeInBits() >= 32)
13022       return SDValue();
13023     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13024     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13025   }
13026   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13027          "Invalid TRUNCATE operation");
13028
13029   // move vector to mask - truncate solution for SKX
13030   if (VT.getVectorElementType() == MVT::i1) {
13031     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13032         Subtarget->hasBWI())
13033       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13034     if ((InVT.is256BitVector() || InVT.is128BitVector())
13035         && InVT.getScalarSizeInBits() <= 16 &&
13036         Subtarget->hasBWI() && Subtarget->hasVLX())
13037       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13038     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13039         Subtarget->hasDQI())
13040       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13041     if ((InVT.is256BitVector() || InVT.is128BitVector())
13042         && InVT.getScalarSizeInBits() >= 32 &&
13043         Subtarget->hasDQI() && Subtarget->hasVLX())
13044       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13045   }
13046
13047   if (VT.getVectorElementType() == MVT::i1) {
13048     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13049     unsigned NumElts = InVT.getVectorNumElements();
13050     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13051     if (InVT.getSizeInBits() < 512) {
13052       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13053       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13054       InVT = ExtVT;
13055     }
13056
13057     SDValue OneV =
13058      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13059     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13060     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13061   }
13062
13063   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13064   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13065       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13066     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13067
13068   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13069     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13070     if (Subtarget->hasInt256()) {
13071       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13072       In = DAG.getBitcast(MVT::v8i32, In);
13073       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13074                                 ShufMask);
13075       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13076                          DAG.getIntPtrConstant(0, DL));
13077     }
13078
13079     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13080                                DAG.getIntPtrConstant(0, DL));
13081     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13082                                DAG.getIntPtrConstant(2, DL));
13083     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13084     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13085     static const int ShufMask[] = {0, 2, 4, 6};
13086     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13087   }
13088
13089   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13090     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13091     if (Subtarget->hasInt256()) {
13092       In = DAG.getBitcast(MVT::v32i8, In);
13093
13094       SmallVector<SDValue,32> pshufbMask;
13095       for (unsigned i = 0; i < 2; ++i) {
13096         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13097         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13098         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13099         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13100         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13101         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13102         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13103         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13104         for (unsigned j = 0; j < 8; ++j)
13105           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13106       }
13107       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13108       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13109       In = DAG.getBitcast(MVT::v4i64, In);
13110
13111       static const int ShufMask[] = {0,  2,  -1,  -1};
13112       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13113                                 &ShufMask[0]);
13114       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13115                        DAG.getIntPtrConstant(0, DL));
13116       return DAG.getBitcast(VT, In);
13117     }
13118
13119     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13120                                DAG.getIntPtrConstant(0, DL));
13121
13122     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13123                                DAG.getIntPtrConstant(4, DL));
13124
13125     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13126     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13127
13128     // The PSHUFB mask:
13129     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13130                                    -1, -1, -1, -1, -1, -1, -1, -1};
13131
13132     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13133     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13134     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13135
13136     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13137     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13138
13139     // The MOVLHPS Mask:
13140     static const int ShufMask2[] = {0, 1, 4, 5};
13141     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13142     return DAG.getBitcast(MVT::v8i16, res);
13143   }
13144
13145   // Handle truncation of V256 to V128 using shuffles.
13146   if (!VT.is128BitVector() || !InVT.is256BitVector())
13147     return SDValue();
13148
13149   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13150
13151   unsigned NumElems = VT.getVectorNumElements();
13152   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13153
13154   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13155   // Prepare truncation shuffle mask
13156   for (unsigned i = 0; i != NumElems; ++i)
13157     MaskVec[i] = i * 2;
13158   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13159                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13160   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13161                      DAG.getIntPtrConstant(0, DL));
13162 }
13163
13164 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13165                                            SelectionDAG &DAG) const {
13166   assert(!Op.getSimpleValueType().isVector());
13167
13168   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13169     /*IsSigned=*/ true, /*IsReplace=*/ false);
13170   SDValue FIST = Vals.first, StackSlot = Vals.second;
13171   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13172   if (!FIST.getNode())
13173     return Op;
13174
13175   if (StackSlot.getNode())
13176     // Load the result.
13177     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13178                        FIST, StackSlot, MachinePointerInfo(),
13179                        false, false, false, 0);
13180
13181   // The node is the result.
13182   return FIST;
13183 }
13184
13185 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13186                                            SelectionDAG &DAG) const {
13187   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13188     /*IsSigned=*/ false, /*IsReplace=*/ false);
13189   SDValue FIST = Vals.first, StackSlot = Vals.second;
13190   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13191   if (!FIST.getNode())
13192     return Op;
13193
13194   if (StackSlot.getNode())
13195     // Load the result.
13196     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13197                        FIST, StackSlot, MachinePointerInfo(),
13198                        false, false, false, 0);
13199
13200   // The node is the result.
13201   return FIST;
13202 }
13203
13204 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13205   SDLoc DL(Op);
13206   MVT VT = Op.getSimpleValueType();
13207   SDValue In = Op.getOperand(0);
13208   MVT SVT = In.getSimpleValueType();
13209
13210   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13211
13212   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13213                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13214                                  In, DAG.getUNDEF(SVT)));
13215 }
13216
13217 /// The only differences between FABS and FNEG are the mask and the logic op.
13218 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13219 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13220   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13221          "Wrong opcode for lowering FABS or FNEG.");
13222
13223   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13224
13225   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13226   // into an FNABS. We'll lower the FABS after that if it is still in use.
13227   if (IsFABS)
13228     for (SDNode *User : Op->uses())
13229       if (User->getOpcode() == ISD::FNEG)
13230         return Op;
13231
13232   SDLoc dl(Op);
13233   MVT VT = Op.getSimpleValueType();
13234
13235   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13236   // decide if we should generate a 16-byte constant mask when we only need 4 or
13237   // 8 bytes for the scalar case.
13238
13239   MVT LogicVT;
13240   MVT EltVT;
13241   unsigned NumElts;
13242
13243   if (VT.isVector()) {
13244     LogicVT = VT;
13245     EltVT = VT.getVectorElementType();
13246     NumElts = VT.getVectorNumElements();
13247   } else {
13248     // There are no scalar bitwise logical SSE/AVX instructions, so we
13249     // generate a 16-byte vector constant and logic op even for the scalar case.
13250     // Using a 16-byte mask allows folding the load of the mask with
13251     // the logic op, so it can save (~4 bytes) on code size.
13252     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13253     EltVT = VT;
13254     NumElts = (VT == MVT::f64) ? 2 : 4;
13255   }
13256
13257   unsigned EltBits = EltVT.getSizeInBits();
13258   LLVMContext *Context = DAG.getContext();
13259   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13260   APInt MaskElt =
13261     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13262   Constant *C = ConstantInt::get(*Context, MaskElt);
13263   C = ConstantVector::getSplat(NumElts, C);
13264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13265   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13266   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13267   SDValue Mask =
13268       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13269                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13270                   false, false, false, Alignment);
13271
13272   SDValue Op0 = Op.getOperand(0);
13273   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13274   unsigned LogicOp =
13275     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13276   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13277
13278   if (VT.isVector())
13279     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13280
13281   // For the scalar case extend to a 128-bit vector, perform the logic op,
13282   // and extract the scalar result back out.
13283   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13284   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13285   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13286                      DAG.getIntPtrConstant(0, dl));
13287 }
13288
13289 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13290   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13291   LLVMContext *Context = DAG.getContext();
13292   SDValue Op0 = Op.getOperand(0);
13293   SDValue Op1 = Op.getOperand(1);
13294   SDLoc dl(Op);
13295   MVT VT = Op.getSimpleValueType();
13296   MVT SrcVT = Op1.getSimpleValueType();
13297
13298   // If second operand is smaller, extend it first.
13299   if (SrcVT.bitsLT(VT)) {
13300     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13301     SrcVT = VT;
13302   }
13303   // And if it is bigger, shrink it first.
13304   if (SrcVT.bitsGT(VT)) {
13305     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13306     SrcVT = VT;
13307   }
13308
13309   // At this point the operands and the result should have the same
13310   // type, and that won't be f80 since that is not custom lowered.
13311
13312   const fltSemantics &Sem =
13313       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13314   const unsigned SizeInBits = VT.getSizeInBits();
13315
13316   SmallVector<Constant *, 4> CV(
13317       VT == MVT::f64 ? 2 : 4,
13318       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13319
13320   // First, clear all bits but the sign bit from the second operand (sign).
13321   CV[0] = ConstantFP::get(*Context,
13322                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13323   Constant *C = ConstantVector::get(CV);
13324   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13325   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13326
13327   // Perform all logic operations as 16-byte vectors because there are no
13328   // scalar FP logic instructions in SSE. This allows load folding of the
13329   // constants into the logic instructions.
13330   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13331   SDValue Mask1 =
13332       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13333                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13334                   false, false, false, 16);
13335   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13336   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13337
13338   // Next, clear the sign bit from the first operand (magnitude).
13339   // If it's a constant, we can clear it here.
13340   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13341     APFloat APF = Op0CN->getValueAPF();
13342     // If the magnitude is a positive zero, the sign bit alone is enough.
13343     if (APF.isPosZero())
13344       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13345                          DAG.getIntPtrConstant(0, dl));
13346     APF.clearSign();
13347     CV[0] = ConstantFP::get(*Context, APF);
13348   } else {
13349     CV[0] = ConstantFP::get(
13350         *Context,
13351         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13352   }
13353   C = ConstantVector::get(CV);
13354   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13355   SDValue Val =
13356       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13357                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13358                   false, false, false, 16);
13359   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13360   if (!isa<ConstantFPSDNode>(Op0)) {
13361     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13362     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13363   }
13364   // OR the magnitude value with the sign bit.
13365   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13366   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13367                      DAG.getIntPtrConstant(0, dl));
13368 }
13369
13370 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13371   SDValue N0 = Op.getOperand(0);
13372   SDLoc dl(Op);
13373   MVT VT = Op.getSimpleValueType();
13374
13375   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13376   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13377                                   DAG.getConstant(1, dl, VT));
13378   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13379 }
13380
13381 // Check whether an OR'd tree is PTEST-able.
13382 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13383                                       SelectionDAG &DAG) {
13384   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13385
13386   if (!Subtarget->hasSSE41())
13387     return SDValue();
13388
13389   if (!Op->hasOneUse())
13390     return SDValue();
13391
13392   SDNode *N = Op.getNode();
13393   SDLoc DL(N);
13394
13395   SmallVector<SDValue, 8> Opnds;
13396   DenseMap<SDValue, unsigned> VecInMap;
13397   SmallVector<SDValue, 8> VecIns;
13398   EVT VT = MVT::Other;
13399
13400   // Recognize a special case where a vector is casted into wide integer to
13401   // test all 0s.
13402   Opnds.push_back(N->getOperand(0));
13403   Opnds.push_back(N->getOperand(1));
13404
13405   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13406     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13407     // BFS traverse all OR'd operands.
13408     if (I->getOpcode() == ISD::OR) {
13409       Opnds.push_back(I->getOperand(0));
13410       Opnds.push_back(I->getOperand(1));
13411       // Re-evaluate the number of nodes to be traversed.
13412       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13413       continue;
13414     }
13415
13416     // Quit if a non-EXTRACT_VECTOR_ELT
13417     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13418       return SDValue();
13419
13420     // Quit if without a constant index.
13421     SDValue Idx = I->getOperand(1);
13422     if (!isa<ConstantSDNode>(Idx))
13423       return SDValue();
13424
13425     SDValue ExtractedFromVec = I->getOperand(0);
13426     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13427     if (M == VecInMap.end()) {
13428       VT = ExtractedFromVec.getValueType();
13429       // Quit if not 128/256-bit vector.
13430       if (!VT.is128BitVector() && !VT.is256BitVector())
13431         return SDValue();
13432       // Quit if not the same type.
13433       if (VecInMap.begin() != VecInMap.end() &&
13434           VT != VecInMap.begin()->first.getValueType())
13435         return SDValue();
13436       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13437       VecIns.push_back(ExtractedFromVec);
13438     }
13439     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13440   }
13441
13442   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13443          "Not extracted from 128-/256-bit vector.");
13444
13445   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13446
13447   for (DenseMap<SDValue, unsigned>::const_iterator
13448         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13449     // Quit if not all elements are used.
13450     if (I->second != FullMask)
13451       return SDValue();
13452   }
13453
13454   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13455
13456   // Cast all vectors into TestVT for PTEST.
13457   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13458     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13459
13460   // If more than one full vectors are evaluated, OR them first before PTEST.
13461   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13462     // Each iteration will OR 2 nodes and append the result until there is only
13463     // 1 node left, i.e. the final OR'd value of all vectors.
13464     SDValue LHS = VecIns[Slot];
13465     SDValue RHS = VecIns[Slot + 1];
13466     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13467   }
13468
13469   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13470                      VecIns.back(), VecIns.back());
13471 }
13472
13473 /// \brief return true if \c Op has a use that doesn't just read flags.
13474 static bool hasNonFlagsUse(SDValue Op) {
13475   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13476        ++UI) {
13477     SDNode *User = *UI;
13478     unsigned UOpNo = UI.getOperandNo();
13479     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13480       // Look pass truncate.
13481       UOpNo = User->use_begin().getOperandNo();
13482       User = *User->use_begin();
13483     }
13484
13485     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13486         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13487       return true;
13488   }
13489   return false;
13490 }
13491
13492 /// Emit nodes that will be selected as "test Op0,Op0", or something
13493 /// equivalent.
13494 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13495                                     SelectionDAG &DAG) const {
13496   if (Op.getValueType() == MVT::i1) {
13497     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13498     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13499                        DAG.getConstant(0, dl, MVT::i8));
13500   }
13501   // CF and OF aren't always set the way we want. Determine which
13502   // of these we need.
13503   bool NeedCF = false;
13504   bool NeedOF = false;
13505   switch (X86CC) {
13506   default: break;
13507   case X86::COND_A: case X86::COND_AE:
13508   case X86::COND_B: case X86::COND_BE:
13509     NeedCF = true;
13510     break;
13511   case X86::COND_G: case X86::COND_GE:
13512   case X86::COND_L: case X86::COND_LE:
13513   case X86::COND_O: case X86::COND_NO: {
13514     // Check if we really need to set the
13515     // Overflow flag. If NoSignedWrap is present
13516     // that is not actually needed.
13517     switch (Op->getOpcode()) {
13518     case ISD::ADD:
13519     case ISD::SUB:
13520     case ISD::MUL:
13521     case ISD::SHL: {
13522       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13523       if (BinNode->Flags.hasNoSignedWrap())
13524         break;
13525     }
13526     default:
13527       NeedOF = true;
13528       break;
13529     }
13530     break;
13531   }
13532   }
13533   // See if we can use the EFLAGS value from the operand instead of
13534   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13535   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13536   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13537     // Emit a CMP with 0, which is the TEST pattern.
13538     //if (Op.getValueType() == MVT::i1)
13539     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13540     //                     DAG.getConstant(0, MVT::i1));
13541     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13542                        DAG.getConstant(0, dl, Op.getValueType()));
13543   }
13544   unsigned Opcode = 0;
13545   unsigned NumOperands = 0;
13546
13547   // Truncate operations may prevent the merge of the SETCC instruction
13548   // and the arithmetic instruction before it. Attempt to truncate the operands
13549   // of the arithmetic instruction and use a reduced bit-width instruction.
13550   bool NeedTruncation = false;
13551   SDValue ArithOp = Op;
13552   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13553     SDValue Arith = Op->getOperand(0);
13554     // Both the trunc and the arithmetic op need to have one user each.
13555     if (Arith->hasOneUse())
13556       switch (Arith.getOpcode()) {
13557         default: break;
13558         case ISD::ADD:
13559         case ISD::SUB:
13560         case ISD::AND:
13561         case ISD::OR:
13562         case ISD::XOR: {
13563           NeedTruncation = true;
13564           ArithOp = Arith;
13565         }
13566       }
13567   }
13568
13569   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13570   // which may be the result of a CAST.  We use the variable 'Op', which is the
13571   // non-casted variable when we check for possible users.
13572   switch (ArithOp.getOpcode()) {
13573   case ISD::ADD:
13574     // Due to an isel shortcoming, be conservative if this add is likely to be
13575     // selected as part of a load-modify-store instruction. When the root node
13576     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13577     // uses of other nodes in the match, such as the ADD in this case. This
13578     // leads to the ADD being left around and reselected, with the result being
13579     // two adds in the output.  Alas, even if none our users are stores, that
13580     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13581     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13582     // climbing the DAG back to the root, and it doesn't seem to be worth the
13583     // effort.
13584     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13585          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13586       if (UI->getOpcode() != ISD::CopyToReg &&
13587           UI->getOpcode() != ISD::SETCC &&
13588           UI->getOpcode() != ISD::STORE)
13589         goto default_case;
13590
13591     if (ConstantSDNode *C =
13592         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13593       // An add of one will be selected as an INC.
13594       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13595         Opcode = X86ISD::INC;
13596         NumOperands = 1;
13597         break;
13598       }
13599
13600       // An add of negative one (subtract of one) will be selected as a DEC.
13601       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13602         Opcode = X86ISD::DEC;
13603         NumOperands = 1;
13604         break;
13605       }
13606     }
13607
13608     // Otherwise use a regular EFLAGS-setting add.
13609     Opcode = X86ISD::ADD;
13610     NumOperands = 2;
13611     break;
13612   case ISD::SHL:
13613   case ISD::SRL:
13614     // If we have a constant logical shift that's only used in a comparison
13615     // against zero turn it into an equivalent AND. This allows turning it into
13616     // a TEST instruction later.
13617     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13618         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13619       EVT VT = Op.getValueType();
13620       unsigned BitWidth = VT.getSizeInBits();
13621       unsigned ShAmt = Op->getConstantOperandVal(1);
13622       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13623         break;
13624       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13625                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13626                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13627       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13628         break;
13629       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13630                                 DAG.getConstant(Mask, dl, VT));
13631       DAG.ReplaceAllUsesWith(Op, New);
13632       Op = New;
13633     }
13634     break;
13635
13636   case ISD::AND:
13637     // If the primary and result isn't used, don't bother using X86ISD::AND,
13638     // because a TEST instruction will be better.
13639     if (!hasNonFlagsUse(Op))
13640       break;
13641     // FALL THROUGH
13642   case ISD::SUB:
13643   case ISD::OR:
13644   case ISD::XOR:
13645     // Due to the ISEL shortcoming noted above, be conservative if this op is
13646     // likely to be selected as part of a load-modify-store instruction.
13647     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13648            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13649       if (UI->getOpcode() == ISD::STORE)
13650         goto default_case;
13651
13652     // Otherwise use a regular EFLAGS-setting instruction.
13653     switch (ArithOp.getOpcode()) {
13654     default: llvm_unreachable("unexpected operator!");
13655     case ISD::SUB: Opcode = X86ISD::SUB; break;
13656     case ISD::XOR: Opcode = X86ISD::XOR; break;
13657     case ISD::AND: Opcode = X86ISD::AND; break;
13658     case ISD::OR: {
13659       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13660         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13661         if (EFLAGS.getNode())
13662           return EFLAGS;
13663       }
13664       Opcode = X86ISD::OR;
13665       break;
13666     }
13667     }
13668
13669     NumOperands = 2;
13670     break;
13671   case X86ISD::ADD:
13672   case X86ISD::SUB:
13673   case X86ISD::INC:
13674   case X86ISD::DEC:
13675   case X86ISD::OR:
13676   case X86ISD::XOR:
13677   case X86ISD::AND:
13678     return SDValue(Op.getNode(), 1);
13679   default:
13680   default_case:
13681     break;
13682   }
13683
13684   // If we found that truncation is beneficial, perform the truncation and
13685   // update 'Op'.
13686   if (NeedTruncation) {
13687     EVT VT = Op.getValueType();
13688     SDValue WideVal = Op->getOperand(0);
13689     EVT WideVT = WideVal.getValueType();
13690     unsigned ConvertedOp = 0;
13691     // Use a target machine opcode to prevent further DAGCombine
13692     // optimizations that may separate the arithmetic operations
13693     // from the setcc node.
13694     switch (WideVal.getOpcode()) {
13695       default: break;
13696       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13697       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13698       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13699       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13700       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13701     }
13702
13703     if (ConvertedOp) {
13704       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13705       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13706         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13707         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13708         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13709       }
13710     }
13711   }
13712
13713   if (Opcode == 0)
13714     // Emit a CMP with 0, which is the TEST pattern.
13715     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13716                        DAG.getConstant(0, dl, Op.getValueType()));
13717
13718   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13719   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13720
13721   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13722   DAG.ReplaceAllUsesWith(Op, New);
13723   return SDValue(New.getNode(), 1);
13724 }
13725
13726 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13727 /// equivalent.
13728 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13729                                    SDLoc dl, SelectionDAG &DAG) const {
13730   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13731     if (C->getAPIntValue() == 0)
13732       return EmitTest(Op0, X86CC, dl, DAG);
13733
13734      if (Op0.getValueType() == MVT::i1)
13735        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13736   }
13737
13738   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13739        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13740     // Do the comparison at i32 if it's smaller, besides the Atom case.
13741     // This avoids subregister aliasing issues. Keep the smaller reference
13742     // if we're optimizing for size, however, as that'll allow better folding
13743     // of memory operations.
13744     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13745         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13746         !Subtarget->isAtom()) {
13747       unsigned ExtendOp =
13748           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13749       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13750       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13751     }
13752     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13753     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13754     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13755                               Op0, Op1);
13756     return SDValue(Sub.getNode(), 1);
13757   }
13758   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13759 }
13760
13761 /// Convert a comparison if required by the subtarget.
13762 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13763                                                  SelectionDAG &DAG) const {
13764   // If the subtarget does not support the FUCOMI instruction, floating-point
13765   // comparisons have to be converted.
13766   if (Subtarget->hasCMov() ||
13767       Cmp.getOpcode() != X86ISD::CMP ||
13768       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13769       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13770     return Cmp;
13771
13772   // The instruction selector will select an FUCOM instruction instead of
13773   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13774   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13775   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13776   SDLoc dl(Cmp);
13777   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13778   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13779   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13780                             DAG.getConstant(8, dl, MVT::i8));
13781   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13782   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13783 }
13784
13785 /// The minimum architected relative accuracy is 2^-12. We need one
13786 /// Newton-Raphson step to have a good float result (24 bits of precision).
13787 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13788                                             DAGCombinerInfo &DCI,
13789                                             unsigned &RefinementSteps,
13790                                             bool &UseOneConstNR) const {
13791   EVT VT = Op.getValueType();
13792   const char *RecipOp;
13793
13794   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13795   // TODO: Add support for AVX512 (v16f32).
13796   // It is likely not profitable to do this for f64 because a double-precision
13797   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13798   // instructions: convert to single, rsqrtss, convert back to double, refine
13799   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13800   // along with FMA, this could be a throughput win.
13801   if (VT == MVT::f32 && Subtarget->hasSSE1())
13802     RecipOp = "sqrtf";
13803   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13804            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13805     RecipOp = "vec-sqrtf";
13806   else
13807     return SDValue();
13808
13809   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13810   if (!Recips.isEnabled(RecipOp))
13811     return SDValue();
13812
13813   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13814   UseOneConstNR = false;
13815   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13816 }
13817
13818 /// The minimum architected relative accuracy is 2^-12. We need one
13819 /// Newton-Raphson step to have a good float result (24 bits of precision).
13820 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13821                                             DAGCombinerInfo &DCI,
13822                                             unsigned &RefinementSteps) const {
13823   EVT VT = Op.getValueType();
13824   const char *RecipOp;
13825
13826   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13827   // TODO: Add support for AVX512 (v16f32).
13828   // It is likely not profitable to do this for f64 because a double-precision
13829   // reciprocal estimate with refinement on x86 prior to FMA requires
13830   // 15 instructions: convert to single, rcpss, convert back to double, refine
13831   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13832   // along with FMA, this could be a throughput win.
13833   if (VT == MVT::f32 && Subtarget->hasSSE1())
13834     RecipOp = "divf";
13835   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13836            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13837     RecipOp = "vec-divf";
13838   else
13839     return SDValue();
13840
13841   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13842   if (!Recips.isEnabled(RecipOp))
13843     return SDValue();
13844
13845   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13846   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13847 }
13848
13849 /// If we have at least two divisions that use the same divisor, convert to
13850 /// multplication by a reciprocal. This may need to be adjusted for a given
13851 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13852 /// This is because we still need one division to calculate the reciprocal and
13853 /// then we need two multiplies by that reciprocal as replacements for the
13854 /// original divisions.
13855 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13856   return 2;
13857 }
13858
13859 static bool isAllOnes(SDValue V) {
13860   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13861   return C && C->isAllOnesValue();
13862 }
13863
13864 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13865 /// if it's possible.
13866 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13867                                      SDLoc dl, SelectionDAG &DAG) const {
13868   SDValue Op0 = And.getOperand(0);
13869   SDValue Op1 = And.getOperand(1);
13870   if (Op0.getOpcode() == ISD::TRUNCATE)
13871     Op0 = Op0.getOperand(0);
13872   if (Op1.getOpcode() == ISD::TRUNCATE)
13873     Op1 = Op1.getOperand(0);
13874
13875   SDValue LHS, RHS;
13876   if (Op1.getOpcode() == ISD::SHL)
13877     std::swap(Op0, Op1);
13878   if (Op0.getOpcode() == ISD::SHL) {
13879     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13880       if (And00C->getZExtValue() == 1) {
13881         // If we looked past a truncate, check that it's only truncating away
13882         // known zeros.
13883         unsigned BitWidth = Op0.getValueSizeInBits();
13884         unsigned AndBitWidth = And.getValueSizeInBits();
13885         if (BitWidth > AndBitWidth) {
13886           APInt Zeros, Ones;
13887           DAG.computeKnownBits(Op0, Zeros, Ones);
13888           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13889             return SDValue();
13890         }
13891         LHS = Op1;
13892         RHS = Op0.getOperand(1);
13893       }
13894   } else if (Op1.getOpcode() == ISD::Constant) {
13895     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13896     uint64_t AndRHSVal = AndRHS->getZExtValue();
13897     SDValue AndLHS = Op0;
13898
13899     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13900       LHS = AndLHS.getOperand(0);
13901       RHS = AndLHS.getOperand(1);
13902     }
13903
13904     // Use BT if the immediate can't be encoded in a TEST instruction.
13905     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13906       LHS = AndLHS;
13907       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13908     }
13909   }
13910
13911   if (LHS.getNode()) {
13912     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13913     // instruction.  Since the shift amount is in-range-or-undefined, we know
13914     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13915     // the encoding for the i16 version is larger than the i32 version.
13916     // Also promote i16 to i32 for performance / code size reason.
13917     if (LHS.getValueType() == MVT::i8 ||
13918         LHS.getValueType() == MVT::i16)
13919       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13920
13921     // If the operand types disagree, extend the shift amount to match.  Since
13922     // BT ignores high bits (like shifts) we can use anyextend.
13923     if (LHS.getValueType() != RHS.getValueType())
13924       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13925
13926     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13927     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13928     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13929                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13930   }
13931
13932   return SDValue();
13933 }
13934
13935 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13936 /// mask CMPs.
13937 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13938                               SDValue &Op1) {
13939   unsigned SSECC;
13940   bool Swap = false;
13941
13942   // SSE Condition code mapping:
13943   //  0 - EQ
13944   //  1 - LT
13945   //  2 - LE
13946   //  3 - UNORD
13947   //  4 - NEQ
13948   //  5 - NLT
13949   //  6 - NLE
13950   //  7 - ORD
13951   switch (SetCCOpcode) {
13952   default: llvm_unreachable("Unexpected SETCC condition");
13953   case ISD::SETOEQ:
13954   case ISD::SETEQ:  SSECC = 0; break;
13955   case ISD::SETOGT:
13956   case ISD::SETGT:  Swap = true; // Fallthrough
13957   case ISD::SETLT:
13958   case ISD::SETOLT: SSECC = 1; break;
13959   case ISD::SETOGE:
13960   case ISD::SETGE:  Swap = true; // Fallthrough
13961   case ISD::SETLE:
13962   case ISD::SETOLE: SSECC = 2; break;
13963   case ISD::SETUO:  SSECC = 3; break;
13964   case ISD::SETUNE:
13965   case ISD::SETNE:  SSECC = 4; break;
13966   case ISD::SETULE: Swap = true; // Fallthrough
13967   case ISD::SETUGE: SSECC = 5; break;
13968   case ISD::SETULT: Swap = true; // Fallthrough
13969   case ISD::SETUGT: SSECC = 6; break;
13970   case ISD::SETO:   SSECC = 7; break;
13971   case ISD::SETUEQ:
13972   case ISD::SETONE: SSECC = 8; break;
13973   }
13974   if (Swap)
13975     std::swap(Op0, Op1);
13976
13977   return SSECC;
13978 }
13979
13980 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13981 // ones, and then concatenate the result back.
13982 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13983   MVT VT = Op.getSimpleValueType();
13984
13985   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13986          "Unsupported value type for operation");
13987
13988   unsigned NumElems = VT.getVectorNumElements();
13989   SDLoc dl(Op);
13990   SDValue CC = Op.getOperand(2);
13991
13992   // Extract the LHS vectors
13993   SDValue LHS = Op.getOperand(0);
13994   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13995   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13996
13997   // Extract the RHS vectors
13998   SDValue RHS = Op.getOperand(1);
13999   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14000   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14001
14002   // Issue the operation on the smaller types and concatenate the result back
14003   MVT EltVT = VT.getVectorElementType();
14004   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14005   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14006                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14007                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14008 }
14009
14010 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14011   SDValue Op0 = Op.getOperand(0);
14012   SDValue Op1 = Op.getOperand(1);
14013   SDValue CC = Op.getOperand(2);
14014   MVT VT = Op.getSimpleValueType();
14015   SDLoc dl(Op);
14016
14017   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
14018          "Unexpected type for boolean compare operation");
14019   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14020   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14021                                DAG.getConstant(-1, dl, VT));
14022   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14023                                DAG.getConstant(-1, dl, VT));
14024   switch (SetCCOpcode) {
14025   default: llvm_unreachable("Unexpected SETCC condition");
14026   case ISD::SETEQ:
14027     // (x == y) -> ~(x ^ y)
14028     return DAG.getNode(ISD::XOR, dl, VT,
14029                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14030                        DAG.getConstant(-1, dl, VT));
14031   case ISD::SETNE:
14032     // (x != y) -> (x ^ y)
14033     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14034   case ISD::SETUGT:
14035   case ISD::SETGT:
14036     // (x > y) -> (x & ~y)
14037     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14038   case ISD::SETULT:
14039   case ISD::SETLT:
14040     // (x < y) -> (~x & y)
14041     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14042   case ISD::SETULE:
14043   case ISD::SETLE:
14044     // (x <= y) -> (~x | y)
14045     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14046   case ISD::SETUGE:
14047   case ISD::SETGE:
14048     // (x >=y) -> (x | ~y)
14049     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14050   }
14051 }
14052
14053 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14054                                      const X86Subtarget *Subtarget) {
14055   SDValue Op0 = Op.getOperand(0);
14056   SDValue Op1 = Op.getOperand(1);
14057   SDValue CC = Op.getOperand(2);
14058   MVT VT = Op.getSimpleValueType();
14059   SDLoc dl(Op);
14060
14061   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14062          Op.getValueType().getScalarType() == MVT::i1 &&
14063          "Cannot set masked compare for this operation");
14064
14065   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14066   unsigned  Opc = 0;
14067   bool Unsigned = false;
14068   bool Swap = false;
14069   unsigned SSECC;
14070   switch (SetCCOpcode) {
14071   default: llvm_unreachable("Unexpected SETCC condition");
14072   case ISD::SETNE:  SSECC = 4; break;
14073   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14074   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14075   case ISD::SETLT:  Swap = true; //fall-through
14076   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14077   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14078   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14079   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14080   case ISD::SETULE: Unsigned = true; //fall-through
14081   case ISD::SETLE:  SSECC = 2; break;
14082   }
14083
14084   if (Swap)
14085     std::swap(Op0, Op1);
14086   if (Opc)
14087     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14088   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14089   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14090                      DAG.getConstant(SSECC, dl, MVT::i8));
14091 }
14092
14093 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14094 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14095 /// return an empty value.
14096 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14097 {
14098   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14099   if (!BV)
14100     return SDValue();
14101
14102   MVT VT = Op1.getSimpleValueType();
14103   MVT EVT = VT.getVectorElementType();
14104   unsigned n = VT.getVectorNumElements();
14105   SmallVector<SDValue, 8> ULTOp1;
14106
14107   for (unsigned i = 0; i < n; ++i) {
14108     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14109     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14110       return SDValue();
14111
14112     // Avoid underflow.
14113     APInt Val = Elt->getAPIntValue();
14114     if (Val == 0)
14115       return SDValue();
14116
14117     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14118   }
14119
14120   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14121 }
14122
14123 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14124                            SelectionDAG &DAG) {
14125   SDValue Op0 = Op.getOperand(0);
14126   SDValue Op1 = Op.getOperand(1);
14127   SDValue CC = Op.getOperand(2);
14128   MVT VT = Op.getSimpleValueType();
14129   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14130   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14131   SDLoc dl(Op);
14132
14133   if (isFP) {
14134 #ifndef NDEBUG
14135     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14136     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14137 #endif
14138
14139     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14140     unsigned Opc = X86ISD::CMPP;
14141     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14142       assert(VT.getVectorNumElements() <= 16);
14143       Opc = X86ISD::CMPM;
14144     }
14145     // In the two special cases we can't handle, emit two comparisons.
14146     if (SSECC == 8) {
14147       unsigned CC0, CC1;
14148       unsigned CombineOpc;
14149       if (SetCCOpcode == ISD::SETUEQ) {
14150         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14151       } else {
14152         assert(SetCCOpcode == ISD::SETONE);
14153         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14154       }
14155
14156       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14157                                  DAG.getConstant(CC0, dl, MVT::i8));
14158       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14159                                  DAG.getConstant(CC1, dl, MVT::i8));
14160       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14161     }
14162     // Handle all other FP comparisons here.
14163     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14164                        DAG.getConstant(SSECC, dl, MVT::i8));
14165   }
14166
14167   // Break 256-bit integer vector compare into smaller ones.
14168   if (VT.is256BitVector() && !Subtarget->hasInt256())
14169     return Lower256IntVSETCC(Op, DAG);
14170
14171   EVT OpVT = Op1.getValueType();
14172   if (OpVT.getVectorElementType() == MVT::i1)
14173     return LowerBoolVSETCC_AVX512(Op, DAG);
14174
14175   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14176   if (Subtarget->hasAVX512()) {
14177     if (Op1.getValueType().is512BitVector() ||
14178         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14179         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14180       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14181
14182     // In AVX-512 architecture setcc returns mask with i1 elements,
14183     // But there is no compare instruction for i8 and i16 elements in KNL.
14184     // We are not talking about 512-bit operands in this case, these
14185     // types are illegal.
14186     if (MaskResult &&
14187         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14188          OpVT.getVectorElementType().getSizeInBits() >= 8))
14189       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14190                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14191   }
14192
14193   // We are handling one of the integer comparisons here.  Since SSE only has
14194   // GT and EQ comparisons for integer, swapping operands and multiple
14195   // operations may be required for some comparisons.
14196   unsigned Opc;
14197   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14198   bool Subus = false;
14199
14200   switch (SetCCOpcode) {
14201   default: llvm_unreachable("Unexpected SETCC condition");
14202   case ISD::SETNE:  Invert = true;
14203   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14204   case ISD::SETLT:  Swap = true;
14205   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14206   case ISD::SETGE:  Swap = true;
14207   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14208                     Invert = true; break;
14209   case ISD::SETULT: Swap = true;
14210   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14211                     FlipSigns = true; break;
14212   case ISD::SETUGE: Swap = true;
14213   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14214                     FlipSigns = true; Invert = true; break;
14215   }
14216
14217   // Special case: Use min/max operations for SETULE/SETUGE
14218   MVT VET = VT.getVectorElementType();
14219   bool hasMinMax =
14220        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14221     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14222
14223   if (hasMinMax) {
14224     switch (SetCCOpcode) {
14225     default: break;
14226     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14227     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14228     }
14229
14230     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14231   }
14232
14233   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14234   if (!MinMax && hasSubus) {
14235     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14236     // Op0 u<= Op1:
14237     //   t = psubus Op0, Op1
14238     //   pcmpeq t, <0..0>
14239     switch (SetCCOpcode) {
14240     default: break;
14241     case ISD::SETULT: {
14242       // If the comparison is against a constant we can turn this into a
14243       // setule.  With psubus, setule does not require a swap.  This is
14244       // beneficial because the constant in the register is no longer
14245       // destructed as the destination so it can be hoisted out of a loop.
14246       // Only do this pre-AVX since vpcmp* is no longer destructive.
14247       if (Subtarget->hasAVX())
14248         break;
14249       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14250       if (ULEOp1.getNode()) {
14251         Op1 = ULEOp1;
14252         Subus = true; Invert = false; Swap = false;
14253       }
14254       break;
14255     }
14256     // Psubus is better than flip-sign because it requires no inversion.
14257     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14258     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14259     }
14260
14261     if (Subus) {
14262       Opc = X86ISD::SUBUS;
14263       FlipSigns = false;
14264     }
14265   }
14266
14267   if (Swap)
14268     std::swap(Op0, Op1);
14269
14270   // Check that the operation in question is available (most are plain SSE2,
14271   // but PCMPGTQ and PCMPEQQ have different requirements).
14272   if (VT == MVT::v2i64) {
14273     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14274       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14275
14276       // First cast everything to the right type.
14277       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14278       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14279
14280       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14281       // bits of the inputs before performing those operations. The lower
14282       // compare is always unsigned.
14283       SDValue SB;
14284       if (FlipSigns) {
14285         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14286       } else {
14287         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14288         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14289         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14290                          Sign, Zero, Sign, Zero);
14291       }
14292       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14293       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14294
14295       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14296       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14297       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14298
14299       // Create masks for only the low parts/high parts of the 64 bit integers.
14300       static const int MaskHi[] = { 1, 1, 3, 3 };
14301       static const int MaskLo[] = { 0, 0, 2, 2 };
14302       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14303       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14304       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14305
14306       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14307       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14308
14309       if (Invert)
14310         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14311
14312       return DAG.getBitcast(VT, Result);
14313     }
14314
14315     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14316       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14317       // pcmpeqd + pshufd + pand.
14318       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14319
14320       // First cast everything to the right type.
14321       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14322       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14323
14324       // Do the compare.
14325       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14326
14327       // Make sure the lower and upper halves are both all-ones.
14328       static const int Mask[] = { 1, 0, 3, 2 };
14329       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14330       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14331
14332       if (Invert)
14333         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14334
14335       return DAG.getBitcast(VT, Result);
14336     }
14337   }
14338
14339   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14340   // bits of the inputs before performing those operations.
14341   if (FlipSigns) {
14342     EVT EltVT = VT.getVectorElementType();
14343     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14344                                  VT);
14345     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14346     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14347   }
14348
14349   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14350
14351   // If the logical-not of the result is required, perform that now.
14352   if (Invert)
14353     Result = DAG.getNOT(dl, Result, VT);
14354
14355   if (MinMax)
14356     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14357
14358   if (Subus)
14359     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14360                          getZeroVector(VT, Subtarget, DAG, dl));
14361
14362   return Result;
14363 }
14364
14365 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14366
14367   MVT VT = Op.getSimpleValueType();
14368
14369   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14370
14371   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14372          && "SetCC type must be 8-bit or 1-bit integer");
14373   SDValue Op0 = Op.getOperand(0);
14374   SDValue Op1 = Op.getOperand(1);
14375   SDLoc dl(Op);
14376   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14377
14378   // Optimize to BT if possible.
14379   // Lower (X & (1 << N)) == 0 to BT(X, N).
14380   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14381   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14382   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14383       Op1.getOpcode() == ISD::Constant &&
14384       cast<ConstantSDNode>(Op1)->isNullValue() &&
14385       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14386     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14387     if (NewSetCC.getNode()) {
14388       if (VT == MVT::i1)
14389         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14390       return NewSetCC;
14391     }
14392   }
14393
14394   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14395   // these.
14396   if (Op1.getOpcode() == ISD::Constant &&
14397       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14398        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14399       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14400
14401     // If the input is a setcc, then reuse the input setcc or use a new one with
14402     // the inverted condition.
14403     if (Op0.getOpcode() == X86ISD::SETCC) {
14404       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14405       bool Invert = (CC == ISD::SETNE) ^
14406         cast<ConstantSDNode>(Op1)->isNullValue();
14407       if (!Invert)
14408         return Op0;
14409
14410       CCode = X86::GetOppositeBranchCondition(CCode);
14411       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14412                                   DAG.getConstant(CCode, dl, MVT::i8),
14413                                   Op0.getOperand(1));
14414       if (VT == MVT::i1)
14415         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14416       return SetCC;
14417     }
14418   }
14419   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14420       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14421       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14422
14423     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14424     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14425   }
14426
14427   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14428   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14429   if (X86CC == X86::COND_INVALID)
14430     return SDValue();
14431
14432   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14433   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14434   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14435                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14436   if (VT == MVT::i1)
14437     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14438   return SetCC;
14439 }
14440
14441 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14442 static bool isX86LogicalCmp(SDValue Op) {
14443   unsigned Opc = Op.getNode()->getOpcode();
14444   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14445       Opc == X86ISD::SAHF)
14446     return true;
14447   if (Op.getResNo() == 1 &&
14448       (Opc == X86ISD::ADD ||
14449        Opc == X86ISD::SUB ||
14450        Opc == X86ISD::ADC ||
14451        Opc == X86ISD::SBB ||
14452        Opc == X86ISD::SMUL ||
14453        Opc == X86ISD::UMUL ||
14454        Opc == X86ISD::INC ||
14455        Opc == X86ISD::DEC ||
14456        Opc == X86ISD::OR ||
14457        Opc == X86ISD::XOR ||
14458        Opc == X86ISD::AND))
14459     return true;
14460
14461   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14462     return true;
14463
14464   return false;
14465 }
14466
14467 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14468   if (V.getOpcode() != ISD::TRUNCATE)
14469     return false;
14470
14471   SDValue VOp0 = V.getOperand(0);
14472   unsigned InBits = VOp0.getValueSizeInBits();
14473   unsigned Bits = V.getValueSizeInBits();
14474   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14475 }
14476
14477 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14478   bool addTest = true;
14479   SDValue Cond  = Op.getOperand(0);
14480   SDValue Op1 = Op.getOperand(1);
14481   SDValue Op2 = Op.getOperand(2);
14482   SDLoc DL(Op);
14483   EVT VT = Op1.getValueType();
14484   SDValue CC;
14485
14486   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14487   // are available or VBLENDV if AVX is available.
14488   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14489   if (Cond.getOpcode() == ISD::SETCC &&
14490       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14491        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14492       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14493     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14494     int SSECC = translateX86FSETCC(
14495         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14496
14497     if (SSECC != 8) {
14498       if (Subtarget->hasAVX512()) {
14499         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14500                                   DAG.getConstant(SSECC, DL, MVT::i8));
14501         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14502       }
14503
14504       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14505                                 DAG.getConstant(SSECC, DL, MVT::i8));
14506
14507       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14508       // of 3 logic instructions for size savings and potentially speed.
14509       // Unfortunately, there is no scalar form of VBLENDV.
14510
14511       // If either operand is a constant, don't try this. We can expect to
14512       // optimize away at least one of the logic instructions later in that
14513       // case, so that sequence would be faster than a variable blend.
14514
14515       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14516       // uses XMM0 as the selection register. That may need just as many
14517       // instructions as the AND/ANDN/OR sequence due to register moves, so
14518       // don't bother.
14519
14520       if (Subtarget->hasAVX() &&
14521           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14522
14523         // Convert to vectors, do a VSELECT, and convert back to scalar.
14524         // All of the conversions should be optimized away.
14525
14526         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14527         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14528         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14529         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14530
14531         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14532         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14533
14534         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14535
14536         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14537                            VSel, DAG.getIntPtrConstant(0, DL));
14538       }
14539       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14540       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14541       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14542     }
14543   }
14544
14545   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14546     SDValue Op1Scalar;
14547     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14548       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14549     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14550       Op1Scalar = Op1.getOperand(0);
14551     SDValue Op2Scalar;
14552     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14553       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14554     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14555       Op2Scalar = Op2.getOperand(0);
14556     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14557       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14558                                       Op1Scalar.getValueType(),
14559                                       Cond, Op1Scalar, Op2Scalar);
14560       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14561         return DAG.getBitcast(VT, newSelect);
14562       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14563       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14564                          DAG.getIntPtrConstant(0, DL));
14565     }
14566   }
14567
14568   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14569     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14570     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14571                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14572     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14573                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14574     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14575                                     Cond, Op1, Op2);
14576     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14577   }
14578
14579   if (Cond.getOpcode() == ISD::SETCC) {
14580     SDValue NewCond = LowerSETCC(Cond, DAG);
14581     if (NewCond.getNode())
14582       Cond = NewCond;
14583   }
14584
14585   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14586   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14587   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14588   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14589   if (Cond.getOpcode() == X86ISD::SETCC &&
14590       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14591       isZero(Cond.getOperand(1).getOperand(1))) {
14592     SDValue Cmp = Cond.getOperand(1);
14593
14594     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14595
14596     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14597         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14598       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14599
14600       SDValue CmpOp0 = Cmp.getOperand(0);
14601       // Apply further optimizations for special cases
14602       // (select (x != 0), -1, 0) -> neg & sbb
14603       // (select (x == 0), 0, -1) -> neg & sbb
14604       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14605         if (YC->isNullValue() &&
14606             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14607           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14608           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14609                                     DAG.getConstant(0, DL,
14610                                                     CmpOp0.getValueType()),
14611                                     CmpOp0);
14612           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14613                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14614                                     SDValue(Neg.getNode(), 1));
14615           return Res;
14616         }
14617
14618       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14619                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14620       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14621
14622       SDValue Res =   // Res = 0 or -1.
14623         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14624                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14625
14626       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14627         Res = DAG.getNOT(DL, Res, Res.getValueType());
14628
14629       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14630       if (!N2C || !N2C->isNullValue())
14631         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14632       return Res;
14633     }
14634   }
14635
14636   // Look past (and (setcc_carry (cmp ...)), 1).
14637   if (Cond.getOpcode() == ISD::AND &&
14638       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14639     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14640     if (C && C->getAPIntValue() == 1)
14641       Cond = Cond.getOperand(0);
14642   }
14643
14644   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14645   // setting operand in place of the X86ISD::SETCC.
14646   unsigned CondOpcode = Cond.getOpcode();
14647   if (CondOpcode == X86ISD::SETCC ||
14648       CondOpcode == X86ISD::SETCC_CARRY) {
14649     CC = Cond.getOperand(0);
14650
14651     SDValue Cmp = Cond.getOperand(1);
14652     unsigned Opc = Cmp.getOpcode();
14653     MVT VT = Op.getSimpleValueType();
14654
14655     bool IllegalFPCMov = false;
14656     if (VT.isFloatingPoint() && !VT.isVector() &&
14657         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14658       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14659
14660     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14661         Opc == X86ISD::BT) { // FIXME
14662       Cond = Cmp;
14663       addTest = false;
14664     }
14665   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14666              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14667              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14668               Cond.getOperand(0).getValueType() != MVT::i8)) {
14669     SDValue LHS = Cond.getOperand(0);
14670     SDValue RHS = Cond.getOperand(1);
14671     unsigned X86Opcode;
14672     unsigned X86Cond;
14673     SDVTList VTs;
14674     switch (CondOpcode) {
14675     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14676     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14677     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14678     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14679     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14680     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14681     default: llvm_unreachable("unexpected overflowing operator");
14682     }
14683     if (CondOpcode == ISD::UMULO)
14684       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14685                           MVT::i32);
14686     else
14687       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14688
14689     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14690
14691     if (CondOpcode == ISD::UMULO)
14692       Cond = X86Op.getValue(2);
14693     else
14694       Cond = X86Op.getValue(1);
14695
14696     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14697     addTest = false;
14698   }
14699
14700   if (addTest) {
14701     // Look past the truncate if the high bits are known zero.
14702     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14703       Cond = Cond.getOperand(0);
14704
14705     // We know the result of AND is compared against zero. Try to match
14706     // it to BT.
14707     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14708       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14709       if (NewSetCC.getNode()) {
14710         CC = NewSetCC.getOperand(0);
14711         Cond = NewSetCC.getOperand(1);
14712         addTest = false;
14713       }
14714     }
14715   }
14716
14717   if (addTest) {
14718     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14719     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14720   }
14721
14722   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14723   // a <  b ?  0 : -1 -> RES = setcc_carry
14724   // a >= b ? -1 :  0 -> RES = setcc_carry
14725   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14726   if (Cond.getOpcode() == X86ISD::SUB) {
14727     Cond = ConvertCmpIfNecessary(Cond, DAG);
14728     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14729
14730     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14731         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14732       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14733                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14734                                 Cond);
14735       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14736         return DAG.getNOT(DL, Res, Res.getValueType());
14737       return Res;
14738     }
14739   }
14740
14741   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14742   // widen the cmov and push the truncate through. This avoids introducing a new
14743   // branch during isel and doesn't add any extensions.
14744   if (Op.getValueType() == MVT::i8 &&
14745       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14746     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14747     if (T1.getValueType() == T2.getValueType() &&
14748         // Blacklist CopyFromReg to avoid partial register stalls.
14749         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14750       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14751       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14752       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14753     }
14754   }
14755
14756   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14757   // condition is true.
14758   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14759   SDValue Ops[] = { Op2, Op1, CC, Cond };
14760   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14761 }
14762
14763 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14764                                        const X86Subtarget *Subtarget,
14765                                        SelectionDAG &DAG) {
14766   MVT VT = Op->getSimpleValueType(0);
14767   SDValue In = Op->getOperand(0);
14768   MVT InVT = In.getSimpleValueType();
14769   MVT VTElt = VT.getVectorElementType();
14770   MVT InVTElt = InVT.getVectorElementType();
14771   SDLoc dl(Op);
14772
14773   // SKX processor
14774   if ((InVTElt == MVT::i1) &&
14775       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14776         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14777
14778        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14779         VTElt.getSizeInBits() <= 16)) ||
14780
14781        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14782         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14783
14784        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14785         VTElt.getSizeInBits() >= 32))))
14786     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14787
14788   unsigned int NumElts = VT.getVectorNumElements();
14789
14790   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14791     return SDValue();
14792
14793   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14794     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14795       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14796     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14797   }
14798
14799   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14800   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14801   SDValue NegOne =
14802    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14803                    ExtVT);
14804   SDValue Zero =
14805    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14806
14807   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14808   if (VT.is512BitVector())
14809     return V;
14810   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14811 }
14812
14813 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14814                                              const X86Subtarget *Subtarget,
14815                                              SelectionDAG &DAG) {
14816   SDValue In = Op->getOperand(0);
14817   MVT VT = Op->getSimpleValueType(0);
14818   MVT InVT = In.getSimpleValueType();
14819   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14820
14821   MVT InSVT = InVT.getScalarType();
14822   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14823
14824   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14825     return SDValue();
14826   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14827     return SDValue();
14828
14829   SDLoc dl(Op);
14830
14831   // SSE41 targets can use the pmovsx* instructions directly.
14832   if (Subtarget->hasSSE41())
14833     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14834
14835   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14836   SDValue Curr = In;
14837   MVT CurrVT = InVT;
14838
14839   // As SRAI is only available on i16/i32 types, we expand only up to i32
14840   // and handle i64 separately.
14841   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14842     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14843     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14844     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14845     Curr = DAG.getBitcast(CurrVT, Curr);
14846   }
14847
14848   SDValue SignExt = Curr;
14849   if (CurrVT != InVT) {
14850     unsigned SignExtShift =
14851         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14852     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14853                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14854   }
14855
14856   if (CurrVT == VT)
14857     return SignExt;
14858
14859   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14860     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14861                                DAG.getConstant(31, dl, MVT::i8));
14862     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14863     return DAG.getBitcast(VT, Ext);
14864   }
14865
14866   return SDValue();
14867 }
14868
14869 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14870                                 SelectionDAG &DAG) {
14871   MVT VT = Op->getSimpleValueType(0);
14872   SDValue In = Op->getOperand(0);
14873   MVT InVT = In.getSimpleValueType();
14874   SDLoc dl(Op);
14875
14876   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14877     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14878
14879   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14880       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14881       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14882     return SDValue();
14883
14884   if (Subtarget->hasInt256())
14885     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14886
14887   // Optimize vectors in AVX mode
14888   // Sign extend  v8i16 to v8i32 and
14889   //              v4i32 to v4i64
14890   //
14891   // Divide input vector into two parts
14892   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14893   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14894   // concat the vectors to original VT
14895
14896   unsigned NumElems = InVT.getVectorNumElements();
14897   SDValue Undef = DAG.getUNDEF(InVT);
14898
14899   SmallVector<int,8> ShufMask1(NumElems, -1);
14900   for (unsigned i = 0; i != NumElems/2; ++i)
14901     ShufMask1[i] = i;
14902
14903   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14904
14905   SmallVector<int,8> ShufMask2(NumElems, -1);
14906   for (unsigned i = 0; i != NumElems/2; ++i)
14907     ShufMask2[i] = i + NumElems/2;
14908
14909   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14910
14911   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14912                                 VT.getVectorNumElements()/2);
14913
14914   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14915   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14916
14917   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14918 }
14919
14920 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14921 // may emit an illegal shuffle but the expansion is still better than scalar
14922 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14923 // we'll emit a shuffle and a arithmetic shift.
14924 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14925 // TODO: It is possible to support ZExt by zeroing the undef values during
14926 // the shuffle phase or after the shuffle.
14927 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14928                                  SelectionDAG &DAG) {
14929   MVT RegVT = Op.getSimpleValueType();
14930   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14931   assert(RegVT.isInteger() &&
14932          "We only custom lower integer vector sext loads.");
14933
14934   // Nothing useful we can do without SSE2 shuffles.
14935   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14936
14937   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14938   SDLoc dl(Ld);
14939   EVT MemVT = Ld->getMemoryVT();
14940   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14941   unsigned RegSz = RegVT.getSizeInBits();
14942
14943   ISD::LoadExtType Ext = Ld->getExtensionType();
14944
14945   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14946          && "Only anyext and sext are currently implemented.");
14947   assert(MemVT != RegVT && "Cannot extend to the same type");
14948   assert(MemVT.isVector() && "Must load a vector from memory");
14949
14950   unsigned NumElems = RegVT.getVectorNumElements();
14951   unsigned MemSz = MemVT.getSizeInBits();
14952   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14953
14954   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14955     // The only way in which we have a legal 256-bit vector result but not the
14956     // integer 256-bit operations needed to directly lower a sextload is if we
14957     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14958     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14959     // correctly legalized. We do this late to allow the canonical form of
14960     // sextload to persist throughout the rest of the DAG combiner -- it wants
14961     // to fold together any extensions it can, and so will fuse a sign_extend
14962     // of an sextload into a sextload targeting a wider value.
14963     SDValue Load;
14964     if (MemSz == 128) {
14965       // Just switch this to a normal load.
14966       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14967                                        "it must be a legal 128-bit vector "
14968                                        "type!");
14969       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14970                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14971                   Ld->isInvariant(), Ld->getAlignment());
14972     } else {
14973       assert(MemSz < 128 &&
14974              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14975       // Do an sext load to a 128-bit vector type. We want to use the same
14976       // number of elements, but elements half as wide. This will end up being
14977       // recursively lowered by this routine, but will succeed as we definitely
14978       // have all the necessary features if we're using AVX1.
14979       EVT HalfEltVT =
14980           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14981       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14982       Load =
14983           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14984                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14985                          Ld->isNonTemporal(), Ld->isInvariant(),
14986                          Ld->getAlignment());
14987     }
14988
14989     // Replace chain users with the new chain.
14990     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14991     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14992
14993     // Finally, do a normal sign-extend to the desired register.
14994     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14995   }
14996
14997   // All sizes must be a power of two.
14998   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14999          "Non-power-of-two elements are not custom lowered!");
15000
15001   // Attempt to load the original value using scalar loads.
15002   // Find the largest scalar type that divides the total loaded size.
15003   MVT SclrLoadTy = MVT::i8;
15004   for (MVT Tp : MVT::integer_valuetypes()) {
15005     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15006       SclrLoadTy = Tp;
15007     }
15008   }
15009
15010   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15011   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15012       (64 <= MemSz))
15013     SclrLoadTy = MVT::f64;
15014
15015   // Calculate the number of scalar loads that we need to perform
15016   // in order to load our vector from memory.
15017   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15018
15019   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15020          "Can only lower sext loads with a single scalar load!");
15021
15022   unsigned loadRegZize = RegSz;
15023   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15024     loadRegZize = 128;
15025
15026   // Represent our vector as a sequence of elements which are the
15027   // largest scalar that we can load.
15028   EVT LoadUnitVecVT = EVT::getVectorVT(
15029       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15030
15031   // Represent the data using the same element type that is stored in
15032   // memory. In practice, we ''widen'' MemVT.
15033   EVT WideVecVT =
15034       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15035                        loadRegZize / MemVT.getScalarType().getSizeInBits());
15036
15037   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15038          "Invalid vector type");
15039
15040   // We can't shuffle using an illegal type.
15041   assert(TLI.isTypeLegal(WideVecVT) &&
15042          "We only lower types that form legal widened vector types");
15043
15044   SmallVector<SDValue, 8> Chains;
15045   SDValue Ptr = Ld->getBasePtr();
15046   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15047                                       TLI.getPointerTy(DAG.getDataLayout()));
15048   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15049
15050   for (unsigned i = 0; i < NumLoads; ++i) {
15051     // Perform a single load.
15052     SDValue ScalarLoad =
15053         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15054                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15055                     Ld->getAlignment());
15056     Chains.push_back(ScalarLoad.getValue(1));
15057     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15058     // another round of DAGCombining.
15059     if (i == 0)
15060       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15061     else
15062       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15063                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15064
15065     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15066   }
15067
15068   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15069
15070   // Bitcast the loaded value to a vector of the original element type, in
15071   // the size of the target vector type.
15072   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15073   unsigned SizeRatio = RegSz / MemSz;
15074
15075   if (Ext == ISD::SEXTLOAD) {
15076     // If we have SSE4.1, we can directly emit a VSEXT node.
15077     if (Subtarget->hasSSE41()) {
15078       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15079       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15080       return Sext;
15081     }
15082
15083     // Otherwise we'll shuffle the small elements in the high bits of the
15084     // larger type and perform an arithmetic shift. If the shift is not legal
15085     // it's better to scalarize.
15086     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
15087            "We can't implement a sext load without an arithmetic right shift!");
15088
15089     // Redistribute the loaded elements into the different locations.
15090     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15091     for (unsigned i = 0; i != NumElems; ++i)
15092       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
15093
15094     SDValue Shuff = DAG.getVectorShuffle(
15095         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15096
15097     Shuff = DAG.getBitcast(RegVT, Shuff);
15098
15099     // Build the arithmetic shift.
15100     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
15101                    MemVT.getVectorElementType().getSizeInBits();
15102     Shuff =
15103         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
15104                     DAG.getConstant(Amt, dl, RegVT));
15105
15106     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15107     return Shuff;
15108   }
15109
15110   // Redistribute the loaded elements into the different locations.
15111   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15112   for (unsigned i = 0; i != NumElems; ++i)
15113     ShuffleVec[i * SizeRatio] = i;
15114
15115   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15116                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15117
15118   // Bitcast to the requested type.
15119   Shuff = DAG.getBitcast(RegVT, Shuff);
15120   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15121   return Shuff;
15122 }
15123
15124 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15125 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15126 // from the AND / OR.
15127 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15128   Opc = Op.getOpcode();
15129   if (Opc != ISD::OR && Opc != ISD::AND)
15130     return false;
15131   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15132           Op.getOperand(0).hasOneUse() &&
15133           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15134           Op.getOperand(1).hasOneUse());
15135 }
15136
15137 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15138 // 1 and that the SETCC node has a single use.
15139 static bool isXor1OfSetCC(SDValue Op) {
15140   if (Op.getOpcode() != ISD::XOR)
15141     return false;
15142   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15143   if (N1C && N1C->getAPIntValue() == 1) {
15144     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15145       Op.getOperand(0).hasOneUse();
15146   }
15147   return false;
15148 }
15149
15150 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15151   bool addTest = true;
15152   SDValue Chain = Op.getOperand(0);
15153   SDValue Cond  = Op.getOperand(1);
15154   SDValue Dest  = Op.getOperand(2);
15155   SDLoc dl(Op);
15156   SDValue CC;
15157   bool Inverted = false;
15158
15159   if (Cond.getOpcode() == ISD::SETCC) {
15160     // Check for setcc([su]{add,sub,mul}o == 0).
15161     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15162         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15163         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15164         Cond.getOperand(0).getResNo() == 1 &&
15165         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15166          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15167          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15168          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15169          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15170          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15171       Inverted = true;
15172       Cond = Cond.getOperand(0);
15173     } else {
15174       SDValue NewCond = LowerSETCC(Cond, DAG);
15175       if (NewCond.getNode())
15176         Cond = NewCond;
15177     }
15178   }
15179 #if 0
15180   // FIXME: LowerXALUO doesn't handle these!!
15181   else if (Cond.getOpcode() == X86ISD::ADD  ||
15182            Cond.getOpcode() == X86ISD::SUB  ||
15183            Cond.getOpcode() == X86ISD::SMUL ||
15184            Cond.getOpcode() == X86ISD::UMUL)
15185     Cond = LowerXALUO(Cond, DAG);
15186 #endif
15187
15188   // Look pass (and (setcc_carry (cmp ...)), 1).
15189   if (Cond.getOpcode() == ISD::AND &&
15190       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15191     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15192     if (C && C->getAPIntValue() == 1)
15193       Cond = Cond.getOperand(0);
15194   }
15195
15196   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15197   // setting operand in place of the X86ISD::SETCC.
15198   unsigned CondOpcode = Cond.getOpcode();
15199   if (CondOpcode == X86ISD::SETCC ||
15200       CondOpcode == X86ISD::SETCC_CARRY) {
15201     CC = Cond.getOperand(0);
15202
15203     SDValue Cmp = Cond.getOperand(1);
15204     unsigned Opc = Cmp.getOpcode();
15205     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15206     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15207       Cond = Cmp;
15208       addTest = false;
15209     } else {
15210       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15211       default: break;
15212       case X86::COND_O:
15213       case X86::COND_B:
15214         // These can only come from an arithmetic instruction with overflow,
15215         // e.g. SADDO, UADDO.
15216         Cond = Cond.getNode()->getOperand(1);
15217         addTest = false;
15218         break;
15219       }
15220     }
15221   }
15222   CondOpcode = Cond.getOpcode();
15223   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15224       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15225       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15226        Cond.getOperand(0).getValueType() != MVT::i8)) {
15227     SDValue LHS = Cond.getOperand(0);
15228     SDValue RHS = Cond.getOperand(1);
15229     unsigned X86Opcode;
15230     unsigned X86Cond;
15231     SDVTList VTs;
15232     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15233     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15234     // X86ISD::INC).
15235     switch (CondOpcode) {
15236     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15237     case ISD::SADDO:
15238       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15239         if (C->isOne()) {
15240           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15241           break;
15242         }
15243       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15244     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15245     case ISD::SSUBO:
15246       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15247         if (C->isOne()) {
15248           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15249           break;
15250         }
15251       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15252     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15253     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15254     default: llvm_unreachable("unexpected overflowing operator");
15255     }
15256     if (Inverted)
15257       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15258     if (CondOpcode == ISD::UMULO)
15259       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15260                           MVT::i32);
15261     else
15262       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15263
15264     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15265
15266     if (CondOpcode == ISD::UMULO)
15267       Cond = X86Op.getValue(2);
15268     else
15269       Cond = X86Op.getValue(1);
15270
15271     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15272     addTest = false;
15273   } else {
15274     unsigned CondOpc;
15275     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15276       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15277       if (CondOpc == ISD::OR) {
15278         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15279         // two branches instead of an explicit OR instruction with a
15280         // separate test.
15281         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15282             isX86LogicalCmp(Cmp)) {
15283           CC = Cond.getOperand(0).getOperand(0);
15284           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15285                               Chain, Dest, CC, Cmp);
15286           CC = Cond.getOperand(1).getOperand(0);
15287           Cond = Cmp;
15288           addTest = false;
15289         }
15290       } else { // ISD::AND
15291         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15292         // two branches instead of an explicit AND instruction with a
15293         // separate test. However, we only do this if this block doesn't
15294         // have a fall-through edge, because this requires an explicit
15295         // jmp when the condition is false.
15296         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15297             isX86LogicalCmp(Cmp) &&
15298             Op.getNode()->hasOneUse()) {
15299           X86::CondCode CCode =
15300             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15301           CCode = X86::GetOppositeBranchCondition(CCode);
15302           CC = DAG.getConstant(CCode, dl, MVT::i8);
15303           SDNode *User = *Op.getNode()->use_begin();
15304           // Look for an unconditional branch following this conditional branch.
15305           // We need this because we need to reverse the successors in order
15306           // to implement FCMP_OEQ.
15307           if (User->getOpcode() == ISD::BR) {
15308             SDValue FalseBB = User->getOperand(1);
15309             SDNode *NewBR =
15310               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15311             assert(NewBR == User);
15312             (void)NewBR;
15313             Dest = FalseBB;
15314
15315             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15316                                 Chain, Dest, CC, Cmp);
15317             X86::CondCode CCode =
15318               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15319             CCode = X86::GetOppositeBranchCondition(CCode);
15320             CC = DAG.getConstant(CCode, dl, MVT::i8);
15321             Cond = Cmp;
15322             addTest = false;
15323           }
15324         }
15325       }
15326     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15327       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15328       // It should be transformed during dag combiner except when the condition
15329       // is set by a arithmetics with overflow node.
15330       X86::CondCode CCode =
15331         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15332       CCode = X86::GetOppositeBranchCondition(CCode);
15333       CC = DAG.getConstant(CCode, dl, MVT::i8);
15334       Cond = Cond.getOperand(0).getOperand(1);
15335       addTest = false;
15336     } else if (Cond.getOpcode() == ISD::SETCC &&
15337                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15338       // For FCMP_OEQ, we can emit
15339       // two branches instead of an explicit AND instruction with a
15340       // separate test. However, we only do this if this block doesn't
15341       // have a fall-through edge, because this requires an explicit
15342       // jmp when the condition is false.
15343       if (Op.getNode()->hasOneUse()) {
15344         SDNode *User = *Op.getNode()->use_begin();
15345         // Look for an unconditional branch following this conditional branch.
15346         // We need this because we need to reverse the successors in order
15347         // to implement FCMP_OEQ.
15348         if (User->getOpcode() == ISD::BR) {
15349           SDValue FalseBB = User->getOperand(1);
15350           SDNode *NewBR =
15351             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15352           assert(NewBR == User);
15353           (void)NewBR;
15354           Dest = FalseBB;
15355
15356           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15357                                     Cond.getOperand(0), Cond.getOperand(1));
15358           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15359           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15360           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15361                               Chain, Dest, CC, Cmp);
15362           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15363           Cond = Cmp;
15364           addTest = false;
15365         }
15366       }
15367     } else if (Cond.getOpcode() == ISD::SETCC &&
15368                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15369       // For FCMP_UNE, we can emit
15370       // two branches instead of an explicit AND instruction with a
15371       // separate test. However, we only do this if this block doesn't
15372       // have a fall-through edge, because this requires an explicit
15373       // jmp when the condition is false.
15374       if (Op.getNode()->hasOneUse()) {
15375         SDNode *User = *Op.getNode()->use_begin();
15376         // Look for an unconditional branch following this conditional branch.
15377         // We need this because we need to reverse the successors in order
15378         // to implement FCMP_UNE.
15379         if (User->getOpcode() == ISD::BR) {
15380           SDValue FalseBB = User->getOperand(1);
15381           SDNode *NewBR =
15382             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15383           assert(NewBR == User);
15384           (void)NewBR;
15385
15386           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15387                                     Cond.getOperand(0), Cond.getOperand(1));
15388           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15389           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15390           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15391                               Chain, Dest, CC, Cmp);
15392           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15393           Cond = Cmp;
15394           addTest = false;
15395           Dest = FalseBB;
15396         }
15397       }
15398     }
15399   }
15400
15401   if (addTest) {
15402     // Look pass the truncate if the high bits are known zero.
15403     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15404         Cond = Cond.getOperand(0);
15405
15406     // We know the result of AND is compared against zero. Try to match
15407     // it to BT.
15408     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15409       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15410       if (NewSetCC.getNode()) {
15411         CC = NewSetCC.getOperand(0);
15412         Cond = NewSetCC.getOperand(1);
15413         addTest = false;
15414       }
15415     }
15416   }
15417
15418   if (addTest) {
15419     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15420     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15421     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15422   }
15423   Cond = ConvertCmpIfNecessary(Cond, DAG);
15424   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15425                      Chain, Dest, CC, Cond);
15426 }
15427
15428 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15429 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15430 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15431 // that the guard pages used by the OS virtual memory manager are allocated in
15432 // correct sequence.
15433 SDValue
15434 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15435                                            SelectionDAG &DAG) const {
15436   MachineFunction &MF = DAG.getMachineFunction();
15437   bool SplitStack = MF.shouldSplitStack();
15438   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15439                SplitStack;
15440   SDLoc dl(Op);
15441
15442   if (!Lower) {
15443     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15444     SDNode* Node = Op.getNode();
15445
15446     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15447     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15448         " not tell us which reg is the stack pointer!");
15449     EVT VT = Node->getValueType(0);
15450     SDValue Tmp1 = SDValue(Node, 0);
15451     SDValue Tmp2 = SDValue(Node, 1);
15452     SDValue Tmp3 = Node->getOperand(2);
15453     SDValue Chain = Tmp1.getOperand(0);
15454
15455     // Chain the dynamic stack allocation so that it doesn't modify the stack
15456     // pointer when other instructions are using the stack.
15457     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15458         SDLoc(Node));
15459
15460     SDValue Size = Tmp2.getOperand(1);
15461     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15462     Chain = SP.getValue(1);
15463     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15464     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15465     unsigned StackAlign = TFI.getStackAlignment();
15466     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15467     if (Align > StackAlign)
15468       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15469           DAG.getConstant(-(uint64_t)Align, dl, VT));
15470     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15471
15472     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15473         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15474         SDLoc(Node));
15475
15476     SDValue Ops[2] = { Tmp1, Tmp2 };
15477     return DAG.getMergeValues(Ops, dl);
15478   }
15479
15480   // Get the inputs.
15481   SDValue Chain = Op.getOperand(0);
15482   SDValue Size  = Op.getOperand(1);
15483   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15484   EVT VT = Op.getNode()->getValueType(0);
15485
15486   bool Is64Bit = Subtarget->is64Bit();
15487   MVT SPTy = getPointerTy(DAG.getDataLayout());
15488
15489   if (SplitStack) {
15490     MachineRegisterInfo &MRI = MF.getRegInfo();
15491
15492     if (Is64Bit) {
15493       // The 64 bit implementation of segmented stacks needs to clobber both r10
15494       // r11. This makes it impossible to use it along with nested parameters.
15495       const Function *F = MF.getFunction();
15496
15497       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15498            I != E; ++I)
15499         if (I->hasNestAttr())
15500           report_fatal_error("Cannot use segmented stacks with functions that "
15501                              "have nested arguments.");
15502     }
15503
15504     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15505     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15506     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15507     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15508                                 DAG.getRegister(Vreg, SPTy));
15509     SDValue Ops1[2] = { Value, Chain };
15510     return DAG.getMergeValues(Ops1, dl);
15511   } else {
15512     SDValue Flag;
15513     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15514
15515     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15516     Flag = Chain.getValue(1);
15517     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15518
15519     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15520
15521     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15522     unsigned SPReg = RegInfo->getStackRegister();
15523     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15524     Chain = SP.getValue(1);
15525
15526     if (Align) {
15527       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15528                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15529       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15530     }
15531
15532     SDValue Ops1[2] = { SP, Chain };
15533     return DAG.getMergeValues(Ops1, dl);
15534   }
15535 }
15536
15537 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15538   MachineFunction &MF = DAG.getMachineFunction();
15539   auto PtrVT = getPointerTy(MF.getDataLayout());
15540   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15541
15542   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15543   SDLoc DL(Op);
15544
15545   if (!Subtarget->is64Bit() ||
15546       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15547     // vastart just stores the address of the VarArgsFrameIndex slot into the
15548     // memory location argument.
15549     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15550     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15551                         MachinePointerInfo(SV), false, false, 0);
15552   }
15553
15554   // __va_list_tag:
15555   //   gp_offset         (0 - 6 * 8)
15556   //   fp_offset         (48 - 48 + 8 * 16)
15557   //   overflow_arg_area (point to parameters coming in memory).
15558   //   reg_save_area
15559   SmallVector<SDValue, 8> MemOps;
15560   SDValue FIN = Op.getOperand(1);
15561   // Store gp_offset
15562   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15563                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15564                                                DL, MVT::i32),
15565                                FIN, MachinePointerInfo(SV), false, false, 0);
15566   MemOps.push_back(Store);
15567
15568   // Store fp_offset
15569   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15570   Store = DAG.getStore(Op.getOperand(0), DL,
15571                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15572                                        MVT::i32),
15573                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15574   MemOps.push_back(Store);
15575
15576   // Store ptr to overflow_arg_area
15577   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15578   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15579   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15580                        MachinePointerInfo(SV, 8),
15581                        false, false, 0);
15582   MemOps.push_back(Store);
15583
15584   // Store ptr to reg_save_area.
15585   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15586       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15587   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15588   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15589       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15590   MemOps.push_back(Store);
15591   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15592 }
15593
15594 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15595   assert(Subtarget->is64Bit() &&
15596          "LowerVAARG only handles 64-bit va_arg!");
15597   assert(Op.getNode()->getNumOperands() == 4);
15598
15599   MachineFunction &MF = DAG.getMachineFunction();
15600   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15601     // The Win64 ABI uses char* instead of a structure.
15602     return DAG.expandVAArg(Op.getNode());
15603
15604   SDValue Chain = Op.getOperand(0);
15605   SDValue SrcPtr = Op.getOperand(1);
15606   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15607   unsigned Align = Op.getConstantOperandVal(3);
15608   SDLoc dl(Op);
15609
15610   EVT ArgVT = Op.getNode()->getValueType(0);
15611   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15612   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15613   uint8_t ArgMode;
15614
15615   // Decide which area this value should be read from.
15616   // TODO: Implement the AMD64 ABI in its entirety. This simple
15617   // selection mechanism works only for the basic types.
15618   if (ArgVT == MVT::f80) {
15619     llvm_unreachable("va_arg for f80 not yet implemented");
15620   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15621     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15622   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15623     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15624   } else {
15625     llvm_unreachable("Unhandled argument type in LowerVAARG");
15626   }
15627
15628   if (ArgMode == 2) {
15629     // Sanity Check: Make sure using fp_offset makes sense.
15630     assert(!Subtarget->useSoftFloat() &&
15631            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15632            Subtarget->hasSSE1());
15633   }
15634
15635   // Insert VAARG_64 node into the DAG
15636   // VAARG_64 returns two values: Variable Argument Address, Chain
15637   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15638                        DAG.getConstant(ArgMode, dl, MVT::i8),
15639                        DAG.getConstant(Align, dl, MVT::i32)};
15640   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15641   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15642                                           VTs, InstOps, MVT::i64,
15643                                           MachinePointerInfo(SV),
15644                                           /*Align=*/0,
15645                                           /*Volatile=*/false,
15646                                           /*ReadMem=*/true,
15647                                           /*WriteMem=*/true);
15648   Chain = VAARG.getValue(1);
15649
15650   // Load the next argument and return it
15651   return DAG.getLoad(ArgVT, dl,
15652                      Chain,
15653                      VAARG,
15654                      MachinePointerInfo(),
15655                      false, false, false, 0);
15656 }
15657
15658 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15659                            SelectionDAG &DAG) {
15660   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15661   // where a va_list is still an i8*.
15662   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15663   if (Subtarget->isCallingConvWin64(
15664         DAG.getMachineFunction().getFunction()->getCallingConv()))
15665     // Probably a Win64 va_copy.
15666     return DAG.expandVACopy(Op.getNode());
15667
15668   SDValue Chain = Op.getOperand(0);
15669   SDValue DstPtr = Op.getOperand(1);
15670   SDValue SrcPtr = Op.getOperand(2);
15671   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15672   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15673   SDLoc DL(Op);
15674
15675   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15676                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15677                        false, false,
15678                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15679 }
15680
15681 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15682 // amount is a constant. Takes immediate version of shift as input.
15683 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15684                                           SDValue SrcOp, uint64_t ShiftAmt,
15685                                           SelectionDAG &DAG) {
15686   MVT ElementType = VT.getVectorElementType();
15687
15688   // Fold this packed shift into its first operand if ShiftAmt is 0.
15689   if (ShiftAmt == 0)
15690     return SrcOp;
15691
15692   // Check for ShiftAmt >= element width
15693   if (ShiftAmt >= ElementType.getSizeInBits()) {
15694     if (Opc == X86ISD::VSRAI)
15695       ShiftAmt = ElementType.getSizeInBits() - 1;
15696     else
15697       return DAG.getConstant(0, dl, VT);
15698   }
15699
15700   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15701          && "Unknown target vector shift-by-constant node");
15702
15703   // Fold this packed vector shift into a build vector if SrcOp is a
15704   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15705   if (VT == SrcOp.getSimpleValueType() &&
15706       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15707     SmallVector<SDValue, 8> Elts;
15708     unsigned NumElts = SrcOp->getNumOperands();
15709     ConstantSDNode *ND;
15710
15711     switch(Opc) {
15712     default: llvm_unreachable(nullptr);
15713     case X86ISD::VSHLI:
15714       for (unsigned i=0; i!=NumElts; ++i) {
15715         SDValue CurrentOp = SrcOp->getOperand(i);
15716         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15717           Elts.push_back(CurrentOp);
15718           continue;
15719         }
15720         ND = cast<ConstantSDNode>(CurrentOp);
15721         const APInt &C = ND->getAPIntValue();
15722         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15723       }
15724       break;
15725     case X86ISD::VSRLI:
15726       for (unsigned i=0; i!=NumElts; ++i) {
15727         SDValue CurrentOp = SrcOp->getOperand(i);
15728         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15729           Elts.push_back(CurrentOp);
15730           continue;
15731         }
15732         ND = cast<ConstantSDNode>(CurrentOp);
15733         const APInt &C = ND->getAPIntValue();
15734         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15735       }
15736       break;
15737     case X86ISD::VSRAI:
15738       for (unsigned i=0; i!=NumElts; ++i) {
15739         SDValue CurrentOp = SrcOp->getOperand(i);
15740         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15741           Elts.push_back(CurrentOp);
15742           continue;
15743         }
15744         ND = cast<ConstantSDNode>(CurrentOp);
15745         const APInt &C = ND->getAPIntValue();
15746         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15747       }
15748       break;
15749     }
15750
15751     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15752   }
15753
15754   return DAG.getNode(Opc, dl, VT, SrcOp,
15755                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15756 }
15757
15758 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15759 // may or may not be a constant. Takes immediate version of shift as input.
15760 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15761                                    SDValue SrcOp, SDValue ShAmt,
15762                                    SelectionDAG &DAG) {
15763   MVT SVT = ShAmt.getSimpleValueType();
15764   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15765
15766   // Catch shift-by-constant.
15767   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15768     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15769                                       CShAmt->getZExtValue(), DAG);
15770
15771   // Change opcode to non-immediate version
15772   switch (Opc) {
15773     default: llvm_unreachable("Unknown target vector shift node");
15774     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15775     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15776     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15777   }
15778
15779   const X86Subtarget &Subtarget =
15780       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15781   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15782       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15783     // Let the shuffle legalizer expand this shift amount node.
15784     SDValue Op0 = ShAmt.getOperand(0);
15785     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15786     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15787   } else {
15788     // Need to build a vector containing shift amount.
15789     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15790     SmallVector<SDValue, 4> ShOps;
15791     ShOps.push_back(ShAmt);
15792     if (SVT == MVT::i32) {
15793       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15794       ShOps.push_back(DAG.getUNDEF(SVT));
15795     }
15796     ShOps.push_back(DAG.getUNDEF(SVT));
15797
15798     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15799     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15800   }
15801
15802   // The return type has to be a 128-bit type with the same element
15803   // type as the input type.
15804   MVT EltVT = VT.getVectorElementType();
15805   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15806
15807   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15808   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15809 }
15810
15811 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15812 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15813 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15814 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15815                                     SDValue PreservedSrc,
15816                                     const X86Subtarget *Subtarget,
15817                                     SelectionDAG &DAG) {
15818     EVT VT = Op.getValueType();
15819     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15820                                   MVT::i1, VT.getVectorNumElements());
15821     SDValue VMask = SDValue();
15822     unsigned OpcodeSelect = ISD::VSELECT;
15823     SDLoc dl(Op);
15824
15825     assert(MaskVT.isSimple() && "invalid mask type");
15826
15827     if (isAllOnes(Mask))
15828       return Op;
15829
15830     if (MaskVT.bitsGT(Mask.getValueType())) {
15831       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15832                                          MaskVT.getSizeInBits());
15833       VMask = DAG.getBitcast(MaskVT,
15834                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15835     } else {
15836       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15837                                        Mask.getValueType().getSizeInBits());
15838       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15839       // are extracted by EXTRACT_SUBVECTOR.
15840       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15841                           DAG.getBitcast(BitcastVT, Mask),
15842                           DAG.getIntPtrConstant(0, dl));
15843     }
15844
15845     switch (Op.getOpcode()) {
15846       default: break;
15847       case X86ISD::PCMPEQM:
15848       case X86ISD::PCMPGTM:
15849       case X86ISD::CMPM:
15850       case X86ISD::CMPMU:
15851         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15852       case X86ISD::VFPCLASS:
15853         return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15854       case X86ISD::VTRUNC:
15855       case X86ISD::VTRUNCS:
15856       case X86ISD::VTRUNCUS:
15857         // We can't use ISD::VSELECT here because it is not always "Legal"
15858         // for the destination type. For example vpmovqb require only AVX512
15859         // and vselect that can operate on byte element type require BWI
15860         OpcodeSelect = X86ISD::SELECT;
15861         break;
15862     }
15863     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15864       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15865     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15866 }
15867
15868 /// \brief Creates an SDNode for a predicated scalar operation.
15869 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15870 /// The mask is coming as MVT::i8 and it should be truncated
15871 /// to MVT::i1 while lowering masking intrinsics.
15872 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15873 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15874 /// for a scalar instruction.
15875 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15876                                     SDValue PreservedSrc,
15877                                     const X86Subtarget *Subtarget,
15878                                     SelectionDAG &DAG) {
15879   if (isAllOnes(Mask))
15880     return Op;
15881
15882   EVT VT = Op.getValueType();
15883   SDLoc dl(Op);
15884   // The mask should be of type MVT::i1
15885   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15886
15887   if (Op.getOpcode() == X86ISD::FSETCC)
15888     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15889
15890   if (PreservedSrc.getOpcode() == ISD::UNDEF)
15891     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15892   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15893 }
15894
15895 static int getSEHRegistrationNodeSize(const Function *Fn) {
15896   if (!Fn->hasPersonalityFn())
15897     report_fatal_error(
15898         "querying registration node size for function without personality");
15899   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15900   // WinEHStatePass for the full struct definition.
15901   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15902   case EHPersonality::MSVC_X86SEH: return 24;
15903   case EHPersonality::MSVC_CXX: return 16;
15904   default: break;
15905   }
15906   report_fatal_error("can only recover FP for MSVC EH personality functions");
15907 }
15908
15909 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15910 /// function or when returning to a parent frame after catching an exception, we
15911 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15912 /// Here's the math:
15913 ///   RegNodeBase = EntryEBP - RegNodeSize
15914 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15915 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15916 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15917 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15918                                    SDValue EntryEBP) {
15919   MachineFunction &MF = DAG.getMachineFunction();
15920   SDLoc dl;
15921
15922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15923   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15924
15925   // It's possible that the parent function no longer has a personality function
15926   // if the exceptional code was optimized away, in which case we just return
15927   // the incoming EBP.
15928   if (!Fn->hasPersonalityFn())
15929     return EntryEBP;
15930
15931   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15932
15933   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15934   // registration.
15935   MCSymbol *OffsetSym =
15936       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15937           GlobalValue::getRealLinkageName(Fn->getName()));
15938   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15939   SDValue RegNodeFrameOffset =
15940       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15941
15942   // RegNodeBase = EntryEBP - RegNodeSize
15943   // ParentFP = RegNodeBase - RegNodeFrameOffset
15944   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15945                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15946   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15947 }
15948
15949 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15950                                        SelectionDAG &DAG) {
15951   SDLoc dl(Op);
15952   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15953   EVT VT = Op.getValueType();
15954   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15955   if (IntrData) {
15956     switch(IntrData->Type) {
15957     case INTR_TYPE_1OP:
15958       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15959     case INTR_TYPE_2OP:
15960       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15961         Op.getOperand(2));
15962     case INTR_TYPE_2OP_IMM8:
15963       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15964                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15965     case INTR_TYPE_3OP:
15966       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15967         Op.getOperand(2), Op.getOperand(3));
15968     case INTR_TYPE_4OP:
15969       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15970         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15971     case INTR_TYPE_1OP_MASK_RM: {
15972       SDValue Src = Op.getOperand(1);
15973       SDValue PassThru = Op.getOperand(2);
15974       SDValue Mask = Op.getOperand(3);
15975       SDValue RoundingMode;
15976       // We allways add rounding mode to the Node.
15977       // If the rounding mode is not specified, we add the
15978       // "current direction" mode.
15979       if (Op.getNumOperands() == 4)
15980         RoundingMode =
15981           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15982       else
15983         RoundingMode = Op.getOperand(4);
15984       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15985       if (IntrWithRoundingModeOpcode != 0)
15986         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15987             X86::STATIC_ROUNDING::CUR_DIRECTION)
15988           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15989                                       dl, Op.getValueType(), Src, RoundingMode),
15990                                       Mask, PassThru, Subtarget, DAG);
15991       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15992                                               RoundingMode),
15993                                   Mask, PassThru, Subtarget, DAG);
15994     }
15995     case INTR_TYPE_1OP_MASK: {
15996       SDValue Src = Op.getOperand(1);
15997       SDValue PassThru = Op.getOperand(2);
15998       SDValue Mask = Op.getOperand(3);
15999       // We add rounding mode to the Node when
16000       //   - RM Opcode is specified and
16001       //   - RM is not "current direction".
16002       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16003       if (IntrWithRoundingModeOpcode != 0) {
16004         SDValue Rnd = Op.getOperand(4);
16005         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16006         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16007           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16008                                       dl, Op.getValueType(),
16009                                       Src, Rnd),
16010                                       Mask, PassThru, Subtarget, DAG);
16011         }
16012       }
16013       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16014                                   Mask, PassThru, Subtarget, DAG);
16015     }
16016     case INTR_TYPE_SCALAR_MASK: {
16017       SDValue Src1 = Op.getOperand(1);
16018       SDValue Src2 = Op.getOperand(2);
16019       SDValue passThru = Op.getOperand(3);
16020       SDValue Mask = Op.getOperand(4);
16021       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16022                                   Mask, passThru, Subtarget, DAG);
16023     }
16024     case INTR_TYPE_SCALAR_MASK_RM: {
16025       SDValue Src1 = Op.getOperand(1);
16026       SDValue Src2 = Op.getOperand(2);
16027       SDValue Src0 = Op.getOperand(3);
16028       SDValue Mask = Op.getOperand(4);
16029       // There are 2 kinds of intrinsics in this group:
16030       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16031       // (2) With rounding mode and sae - 7 operands.
16032       if (Op.getNumOperands() == 6) {
16033         SDValue Sae  = Op.getOperand(5);
16034         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16035         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16036                                                 Sae),
16037                                     Mask, Src0, Subtarget, DAG);
16038       }
16039       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16040       SDValue RoundingMode  = Op.getOperand(5);
16041       SDValue Sae  = Op.getOperand(6);
16042       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16043                                               RoundingMode, Sae),
16044                                   Mask, Src0, Subtarget, DAG);
16045     }
16046     case INTR_TYPE_2OP_MASK: {
16047       SDValue Src1 = Op.getOperand(1);
16048       SDValue Src2 = Op.getOperand(2);
16049       SDValue PassThru = Op.getOperand(3);
16050       SDValue Mask = Op.getOperand(4);
16051       // We specify 2 possible opcodes for intrinsics with rounding modes.
16052       // First, we check if the intrinsic may have non-default rounding mode,
16053       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16054       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16055       if (IntrWithRoundingModeOpcode != 0) {
16056         SDValue Rnd = Op.getOperand(5);
16057         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16058         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16059           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16060                                       dl, Op.getValueType(),
16061                                       Src1, Src2, Rnd),
16062                                       Mask, PassThru, Subtarget, DAG);
16063         }
16064       }
16065       // TODO: Intrinsics should have fast-math-flags to propagate.
16066       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16067                                   Mask, PassThru, Subtarget, DAG);
16068     }
16069     case INTR_TYPE_2OP_MASK_RM: {
16070       SDValue Src1 = Op.getOperand(1);
16071       SDValue Src2 = Op.getOperand(2);
16072       SDValue PassThru = Op.getOperand(3);
16073       SDValue Mask = Op.getOperand(4);
16074       // We specify 2 possible modes for intrinsics, with/without rounding
16075       // modes.
16076       // First, we check if the intrinsic have rounding mode (6 operands),
16077       // if not, we set rounding mode to "current".
16078       SDValue Rnd;
16079       if (Op.getNumOperands() == 6)
16080         Rnd = Op.getOperand(5);
16081       else
16082         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16083       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16084                                               Src1, Src2, Rnd),
16085                                   Mask, PassThru, Subtarget, DAG);
16086     }
16087     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16088       SDValue Src1 = Op.getOperand(1);
16089       SDValue Src2 = Op.getOperand(2);
16090       SDValue Src3 = Op.getOperand(3);
16091       SDValue PassThru = Op.getOperand(4);
16092       SDValue Mask = Op.getOperand(5);
16093       SDValue Sae  = Op.getOperand(6);
16094
16095       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16096                                               Src2, Src3, Sae),
16097                                   Mask, PassThru, Subtarget, DAG);
16098     }
16099     case INTR_TYPE_3OP_MASK_RM: {
16100       SDValue Src1 = Op.getOperand(1);
16101       SDValue Src2 = Op.getOperand(2);
16102       SDValue Imm = Op.getOperand(3);
16103       SDValue PassThru = Op.getOperand(4);
16104       SDValue Mask = Op.getOperand(5);
16105       // We specify 2 possible modes for intrinsics, with/without rounding
16106       // modes.
16107       // First, we check if the intrinsic have rounding mode (7 operands),
16108       // if not, we set rounding mode to "current".
16109       SDValue Rnd;
16110       if (Op.getNumOperands() == 7)
16111         Rnd = Op.getOperand(6);
16112       else
16113         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16114       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16115         Src1, Src2, Imm, Rnd),
16116         Mask, PassThru, Subtarget, DAG);
16117     }
16118     case INTR_TYPE_3OP_IMM8_MASK:
16119     case INTR_TYPE_3OP_MASK:
16120     case INSERT_SUBVEC: {
16121       SDValue Src1 = Op.getOperand(1);
16122       SDValue Src2 = Op.getOperand(2);
16123       SDValue Src3 = Op.getOperand(3);
16124       SDValue PassThru = Op.getOperand(4);
16125       SDValue Mask = Op.getOperand(5);
16126
16127       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16128         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16129       else if (IntrData->Type == INSERT_SUBVEC) {
16130         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16131         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16132         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16133         Imm *= Src2.getValueType().getVectorNumElements();
16134         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16135       }
16136
16137       // We specify 2 possible opcodes for intrinsics with rounding modes.
16138       // First, we check if the intrinsic may have non-default rounding mode,
16139       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16140       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16141       if (IntrWithRoundingModeOpcode != 0) {
16142         SDValue Rnd = Op.getOperand(6);
16143         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16144         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16145           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16146                                       dl, Op.getValueType(),
16147                                       Src1, Src2, Src3, Rnd),
16148                                       Mask, PassThru, Subtarget, DAG);
16149         }
16150       }
16151       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16152                                               Src1, Src2, Src3),
16153                                   Mask, PassThru, Subtarget, DAG);
16154     }
16155     case VPERM_3OP_MASKZ:
16156     case VPERM_3OP_MASK:
16157     case FMA_OP_MASK3:
16158     case FMA_OP_MASKZ:
16159     case FMA_OP_MASK: {
16160       SDValue Src1 = Op.getOperand(1);
16161       SDValue Src2 = Op.getOperand(2);
16162       SDValue Src3 = Op.getOperand(3);
16163       SDValue Mask = Op.getOperand(4);
16164       EVT VT = Op.getValueType();
16165       SDValue PassThru = SDValue();
16166
16167       // set PassThru element
16168       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16169         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16170       else if (IntrData->Type == FMA_OP_MASK3)
16171         PassThru = Src3;
16172       else
16173         PassThru = Src1;
16174
16175       // We specify 2 possible opcodes for intrinsics with rounding modes.
16176       // First, we check if the intrinsic may have non-default rounding mode,
16177       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16178       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16179       if (IntrWithRoundingModeOpcode != 0) {
16180         SDValue Rnd = Op.getOperand(5);
16181         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16182             X86::STATIC_ROUNDING::CUR_DIRECTION)
16183           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16184                                                   dl, Op.getValueType(),
16185                                                   Src1, Src2, Src3, Rnd),
16186                                       Mask, PassThru, Subtarget, DAG);
16187       }
16188       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16189                                               dl, Op.getValueType(),
16190                                               Src1, Src2, Src3),
16191                                   Mask, PassThru, Subtarget, DAG);
16192     }
16193     case FPCLASS: {
16194       // FPclass intrinsics with mask
16195        SDValue Src1 = Op.getOperand(1);
16196        EVT VT = Src1.getValueType();
16197        EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16198                                       VT.getVectorNumElements());
16199        SDValue Imm = Op.getOperand(2);
16200        SDValue Mask = Op.getOperand(3);
16201        EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16202                                         Mask.getValueType().getSizeInBits());
16203        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16204        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16205                                                  DAG.getTargetConstant(0, dl, MaskVT),
16206                                                  Subtarget, DAG);
16207        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16208                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16209                                  DAG.getIntPtrConstant(0, dl));
16210        return DAG.getBitcast(Op.getValueType(), Res);
16211     }
16212     case CMP_MASK:
16213     case CMP_MASK_CC: {
16214       // Comparison intrinsics with masks.
16215       // Example of transformation:
16216       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16217       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16218       // (i8 (bitcast
16219       //   (v8i1 (insert_subvector undef,
16220       //           (v2i1 (and (PCMPEQM %a, %b),
16221       //                      (extract_subvector
16222       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16223       EVT VT = Op.getOperand(1).getValueType();
16224       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16225                                     VT.getVectorNumElements());
16226       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16227       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16228                                        Mask.getValueType().getSizeInBits());
16229       SDValue Cmp;
16230       if (IntrData->Type == CMP_MASK_CC) {
16231         SDValue CC = Op.getOperand(3);
16232         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16233         // We specify 2 possible opcodes for intrinsics with rounding modes.
16234         // First, we check if the intrinsic may have non-default rounding mode,
16235         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16236         if (IntrData->Opc1 != 0) {
16237           SDValue Rnd = Op.getOperand(5);
16238           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16239               X86::STATIC_ROUNDING::CUR_DIRECTION)
16240             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16241                               Op.getOperand(2), CC, Rnd);
16242         }
16243         //default rounding mode
16244         if(!Cmp.getNode())
16245             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16246                               Op.getOperand(2), CC);
16247
16248       } else {
16249         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16250         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16251                           Op.getOperand(2));
16252       }
16253       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16254                                              DAG.getTargetConstant(0, dl,
16255                                                                    MaskVT),
16256                                              Subtarget, DAG);
16257       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16258                                 DAG.getUNDEF(BitcastVT), CmpMask,
16259                                 DAG.getIntPtrConstant(0, dl));
16260       return DAG.getBitcast(Op.getValueType(), Res);
16261     }
16262     case CMP_MASK_SCALAR_CC: {
16263       SDValue Src1 = Op.getOperand(1);
16264       SDValue Src2 = Op.getOperand(2);
16265       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16266       SDValue Mask = Op.getOperand(4);
16267
16268       SDValue Cmp;
16269       if (IntrData->Opc1 != 0) {
16270         SDValue Rnd = Op.getOperand(5);
16271         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16272             X86::STATIC_ROUNDING::CUR_DIRECTION)
16273           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16274       }
16275       //default rounding mode
16276       if(!Cmp.getNode())
16277         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16278
16279       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16280                                              DAG.getTargetConstant(0, dl,
16281                                                                    MVT::i1),
16282                                              Subtarget, DAG);
16283
16284       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16285                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16286                          DAG.getValueType(MVT::i1));
16287     }
16288     case COMI: { // Comparison intrinsics
16289       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16290       SDValue LHS = Op.getOperand(1);
16291       SDValue RHS = Op.getOperand(2);
16292       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16293       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16294       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16295       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16296                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16297       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16298     }
16299     case VSHIFT:
16300       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16301                                  Op.getOperand(1), Op.getOperand(2), DAG);
16302     case VSHIFT_MASK:
16303       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16304                                                       Op.getSimpleValueType(),
16305                                                       Op.getOperand(1),
16306                                                       Op.getOperand(2), DAG),
16307                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16308                                   DAG);
16309     case COMPRESS_EXPAND_IN_REG: {
16310       SDValue Mask = Op.getOperand(3);
16311       SDValue DataToCompress = Op.getOperand(1);
16312       SDValue PassThru = Op.getOperand(2);
16313       if (isAllOnes(Mask)) // return data as is
16314         return Op.getOperand(1);
16315
16316       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16317                                               DataToCompress),
16318                                   Mask, PassThru, Subtarget, DAG);
16319     }
16320     case BLEND: {
16321       SDValue Mask = Op.getOperand(3);
16322       EVT VT = Op.getValueType();
16323       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16324                                     VT.getVectorNumElements());
16325       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16326                                        Mask.getValueType().getSizeInBits());
16327       SDLoc dl(Op);
16328       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16329                                   DAG.getBitcast(BitcastVT, Mask),
16330                                   DAG.getIntPtrConstant(0, dl));
16331       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16332                          Op.getOperand(2));
16333     }
16334     default:
16335       break;
16336     }
16337   }
16338
16339   switch (IntNo) {
16340   default: return SDValue();    // Don't custom lower most intrinsics.
16341
16342   case Intrinsic::x86_avx2_permd:
16343   case Intrinsic::x86_avx2_permps:
16344     // Operands intentionally swapped. Mask is last operand to intrinsic,
16345     // but second operand for node/instruction.
16346     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16347                        Op.getOperand(2), Op.getOperand(1));
16348
16349   // ptest and testp intrinsics. The intrinsic these come from are designed to
16350   // return an integer value, not just an instruction so lower it to the ptest
16351   // or testp pattern and a setcc for the result.
16352   case Intrinsic::x86_sse41_ptestz:
16353   case Intrinsic::x86_sse41_ptestc:
16354   case Intrinsic::x86_sse41_ptestnzc:
16355   case Intrinsic::x86_avx_ptestz_256:
16356   case Intrinsic::x86_avx_ptestc_256:
16357   case Intrinsic::x86_avx_ptestnzc_256:
16358   case Intrinsic::x86_avx_vtestz_ps:
16359   case Intrinsic::x86_avx_vtestc_ps:
16360   case Intrinsic::x86_avx_vtestnzc_ps:
16361   case Intrinsic::x86_avx_vtestz_pd:
16362   case Intrinsic::x86_avx_vtestc_pd:
16363   case Intrinsic::x86_avx_vtestnzc_pd:
16364   case Intrinsic::x86_avx_vtestz_ps_256:
16365   case Intrinsic::x86_avx_vtestc_ps_256:
16366   case Intrinsic::x86_avx_vtestnzc_ps_256:
16367   case Intrinsic::x86_avx_vtestz_pd_256:
16368   case Intrinsic::x86_avx_vtestc_pd_256:
16369   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16370     bool IsTestPacked = false;
16371     unsigned X86CC;
16372     switch (IntNo) {
16373     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16374     case Intrinsic::x86_avx_vtestz_ps:
16375     case Intrinsic::x86_avx_vtestz_pd:
16376     case Intrinsic::x86_avx_vtestz_ps_256:
16377     case Intrinsic::x86_avx_vtestz_pd_256:
16378       IsTestPacked = true; // Fallthrough
16379     case Intrinsic::x86_sse41_ptestz:
16380     case Intrinsic::x86_avx_ptestz_256:
16381       // ZF = 1
16382       X86CC = X86::COND_E;
16383       break;
16384     case Intrinsic::x86_avx_vtestc_ps:
16385     case Intrinsic::x86_avx_vtestc_pd:
16386     case Intrinsic::x86_avx_vtestc_ps_256:
16387     case Intrinsic::x86_avx_vtestc_pd_256:
16388       IsTestPacked = true; // Fallthrough
16389     case Intrinsic::x86_sse41_ptestc:
16390     case Intrinsic::x86_avx_ptestc_256:
16391       // CF = 1
16392       X86CC = X86::COND_B;
16393       break;
16394     case Intrinsic::x86_avx_vtestnzc_ps:
16395     case Intrinsic::x86_avx_vtestnzc_pd:
16396     case Intrinsic::x86_avx_vtestnzc_ps_256:
16397     case Intrinsic::x86_avx_vtestnzc_pd_256:
16398       IsTestPacked = true; // Fallthrough
16399     case Intrinsic::x86_sse41_ptestnzc:
16400     case Intrinsic::x86_avx_ptestnzc_256:
16401       // ZF and CF = 0
16402       X86CC = X86::COND_A;
16403       break;
16404     }
16405
16406     SDValue LHS = Op.getOperand(1);
16407     SDValue RHS = Op.getOperand(2);
16408     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16409     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16410     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16411     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16412     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16413   }
16414   case Intrinsic::x86_avx512_kortestz_w:
16415   case Intrinsic::x86_avx512_kortestc_w: {
16416     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16417     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16418     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16419     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16420     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16421     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16422     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16423   }
16424
16425   case Intrinsic::x86_sse42_pcmpistria128:
16426   case Intrinsic::x86_sse42_pcmpestria128:
16427   case Intrinsic::x86_sse42_pcmpistric128:
16428   case Intrinsic::x86_sse42_pcmpestric128:
16429   case Intrinsic::x86_sse42_pcmpistrio128:
16430   case Intrinsic::x86_sse42_pcmpestrio128:
16431   case Intrinsic::x86_sse42_pcmpistris128:
16432   case Intrinsic::x86_sse42_pcmpestris128:
16433   case Intrinsic::x86_sse42_pcmpistriz128:
16434   case Intrinsic::x86_sse42_pcmpestriz128: {
16435     unsigned Opcode;
16436     unsigned X86CC;
16437     switch (IntNo) {
16438     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16439     case Intrinsic::x86_sse42_pcmpistria128:
16440       Opcode = X86ISD::PCMPISTRI;
16441       X86CC = X86::COND_A;
16442       break;
16443     case Intrinsic::x86_sse42_pcmpestria128:
16444       Opcode = X86ISD::PCMPESTRI;
16445       X86CC = X86::COND_A;
16446       break;
16447     case Intrinsic::x86_sse42_pcmpistric128:
16448       Opcode = X86ISD::PCMPISTRI;
16449       X86CC = X86::COND_B;
16450       break;
16451     case Intrinsic::x86_sse42_pcmpestric128:
16452       Opcode = X86ISD::PCMPESTRI;
16453       X86CC = X86::COND_B;
16454       break;
16455     case Intrinsic::x86_sse42_pcmpistrio128:
16456       Opcode = X86ISD::PCMPISTRI;
16457       X86CC = X86::COND_O;
16458       break;
16459     case Intrinsic::x86_sse42_pcmpestrio128:
16460       Opcode = X86ISD::PCMPESTRI;
16461       X86CC = X86::COND_O;
16462       break;
16463     case Intrinsic::x86_sse42_pcmpistris128:
16464       Opcode = X86ISD::PCMPISTRI;
16465       X86CC = X86::COND_S;
16466       break;
16467     case Intrinsic::x86_sse42_pcmpestris128:
16468       Opcode = X86ISD::PCMPESTRI;
16469       X86CC = X86::COND_S;
16470       break;
16471     case Intrinsic::x86_sse42_pcmpistriz128:
16472       Opcode = X86ISD::PCMPISTRI;
16473       X86CC = X86::COND_E;
16474       break;
16475     case Intrinsic::x86_sse42_pcmpestriz128:
16476       Opcode = X86ISD::PCMPESTRI;
16477       X86CC = X86::COND_E;
16478       break;
16479     }
16480     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16481     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16482     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16483     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16484                                 DAG.getConstant(X86CC, dl, MVT::i8),
16485                                 SDValue(PCMP.getNode(), 1));
16486     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16487   }
16488
16489   case Intrinsic::x86_sse42_pcmpistri128:
16490   case Intrinsic::x86_sse42_pcmpestri128: {
16491     unsigned Opcode;
16492     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16493       Opcode = X86ISD::PCMPISTRI;
16494     else
16495       Opcode = X86ISD::PCMPESTRI;
16496
16497     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16498     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16499     return DAG.getNode(Opcode, dl, VTs, NewOps);
16500   }
16501
16502   case Intrinsic::x86_seh_lsda: {
16503     // Compute the symbol for the LSDA. We know it'll get emitted later.
16504     MachineFunction &MF = DAG.getMachineFunction();
16505     SDValue Op1 = Op.getOperand(1);
16506     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16507     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16508         GlobalValue::getRealLinkageName(Fn->getName()));
16509
16510     // Generate a simple absolute symbol reference. This intrinsic is only
16511     // supported on 32-bit Windows, which isn't PIC.
16512     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16513     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16514   }
16515
16516   case Intrinsic::x86_seh_recoverfp: {
16517     SDValue FnOp = Op.getOperand(1);
16518     SDValue IncomingFPOp = Op.getOperand(2);
16519     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16520     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16521     if (!Fn)
16522       report_fatal_error(
16523           "llvm.x86.seh.recoverfp must take a function as the first argument");
16524     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16525   }
16526
16527   case Intrinsic::localaddress: {
16528     // Returns one of the stack, base, or frame pointer registers, depending on
16529     // which is used to reference local variables.
16530     MachineFunction &MF = DAG.getMachineFunction();
16531     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16532     unsigned Reg;
16533     if (RegInfo->hasBasePointer(MF))
16534       Reg = RegInfo->getBaseRegister();
16535     else // This function handles the SP or FP case.
16536       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16537     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16538   }
16539   }
16540 }
16541
16542 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16543                               SDValue Src, SDValue Mask, SDValue Base,
16544                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16545                               const X86Subtarget * Subtarget) {
16546   SDLoc dl(Op);
16547   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16548   if (!C)
16549     llvm_unreachable("Invalid scale type");
16550   unsigned ScaleVal = C->getZExtValue();
16551   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16552     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16553
16554   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16555   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16556                              Index.getSimpleValueType().getVectorNumElements());
16557   SDValue MaskInReg;
16558   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16559   if (MaskC)
16560     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16561   else {
16562     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16563                                      Mask.getValueType().getSizeInBits());
16564
16565     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16566     // are extracted by EXTRACT_SUBVECTOR.
16567     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16568                             DAG.getBitcast(BitcastVT, Mask),
16569                             DAG.getIntPtrConstant(0, dl));
16570   }
16571   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16572   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16573   SDValue Segment = DAG.getRegister(0, MVT::i32);
16574   if (Src.getOpcode() == ISD::UNDEF)
16575     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16576   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16577   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16578   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16579   return DAG.getMergeValues(RetOps, dl);
16580 }
16581
16582 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16583                                SDValue Src, SDValue Mask, SDValue Base,
16584                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16585   SDLoc dl(Op);
16586   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16587   if (!C)
16588     llvm_unreachable("Invalid scale type");
16589   unsigned ScaleVal = C->getZExtValue();
16590   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16591     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16592
16593   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16594   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16595   SDValue Segment = DAG.getRegister(0, MVT::i32);
16596   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16597                              Index.getSimpleValueType().getVectorNumElements());
16598   SDValue MaskInReg;
16599   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16600   if (MaskC)
16601     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16602   else {
16603     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16604                                      Mask.getValueType().getSizeInBits());
16605
16606     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16607     // are extracted by EXTRACT_SUBVECTOR.
16608     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16609                             DAG.getBitcast(BitcastVT, Mask),
16610                             DAG.getIntPtrConstant(0, dl));
16611   }
16612   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16613   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16614   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16615   return SDValue(Res, 1);
16616 }
16617
16618 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16619                                SDValue Mask, SDValue Base, SDValue Index,
16620                                SDValue ScaleOp, SDValue Chain) {
16621   SDLoc dl(Op);
16622   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16623   assert(C && "Invalid scale type");
16624   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16625   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16626   SDValue Segment = DAG.getRegister(0, MVT::i32);
16627   EVT MaskVT =
16628     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16629   SDValue MaskInReg;
16630   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16631   if (MaskC)
16632     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16633   else
16634     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16635   //SDVTList VTs = DAG.getVTList(MVT::Other);
16636   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16637   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16638   return SDValue(Res, 0);
16639 }
16640
16641 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16642 // read performance monitor counters (x86_rdpmc).
16643 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16644                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16645                               SmallVectorImpl<SDValue> &Results) {
16646   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16647   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16648   SDValue LO, HI;
16649
16650   // The ECX register is used to select the index of the performance counter
16651   // to read.
16652   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16653                                    N->getOperand(2));
16654   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16655
16656   // Reads the content of a 64-bit performance counter and returns it in the
16657   // registers EDX:EAX.
16658   if (Subtarget->is64Bit()) {
16659     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16660     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16661                             LO.getValue(2));
16662   } else {
16663     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16664     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16665                             LO.getValue(2));
16666   }
16667   Chain = HI.getValue(1);
16668
16669   if (Subtarget->is64Bit()) {
16670     // The EAX register is loaded with the low-order 32 bits. The EDX register
16671     // is loaded with the supported high-order bits of the counter.
16672     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16673                               DAG.getConstant(32, DL, MVT::i8));
16674     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16675     Results.push_back(Chain);
16676     return;
16677   }
16678
16679   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16680   SDValue Ops[] = { LO, HI };
16681   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16682   Results.push_back(Pair);
16683   Results.push_back(Chain);
16684 }
16685
16686 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16687 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16688 // also used to custom lower READCYCLECOUNTER nodes.
16689 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16690                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16691                               SmallVectorImpl<SDValue> &Results) {
16692   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16693   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16694   SDValue LO, HI;
16695
16696   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16697   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16698   // and the EAX register is loaded with the low-order 32 bits.
16699   if (Subtarget->is64Bit()) {
16700     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16701     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16702                             LO.getValue(2));
16703   } else {
16704     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16705     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16706                             LO.getValue(2));
16707   }
16708   SDValue Chain = HI.getValue(1);
16709
16710   if (Opcode == X86ISD::RDTSCP_DAG) {
16711     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16712
16713     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16714     // the ECX register. Add 'ecx' explicitly to the chain.
16715     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16716                                      HI.getValue(2));
16717     // Explicitly store the content of ECX at the location passed in input
16718     // to the 'rdtscp' intrinsic.
16719     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16720                          MachinePointerInfo(), false, false, 0);
16721   }
16722
16723   if (Subtarget->is64Bit()) {
16724     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16725     // the EAX register is loaded with the low-order 32 bits.
16726     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16727                               DAG.getConstant(32, DL, MVT::i8));
16728     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16729     Results.push_back(Chain);
16730     return;
16731   }
16732
16733   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16734   SDValue Ops[] = { LO, HI };
16735   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16736   Results.push_back(Pair);
16737   Results.push_back(Chain);
16738 }
16739
16740 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16741                                      SelectionDAG &DAG) {
16742   SmallVector<SDValue, 2> Results;
16743   SDLoc DL(Op);
16744   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16745                           Results);
16746   return DAG.getMergeValues(Results, DL);
16747 }
16748
16749 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16750                                     SelectionDAG &DAG) {
16751   MachineFunction &MF = DAG.getMachineFunction();
16752   const Function *Fn = MF.getFunction();
16753   SDLoc dl(Op);
16754   SDValue Chain = Op.getOperand(0);
16755
16756   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16757          "using llvm.x86.seh.restoreframe requires a frame pointer");
16758
16759   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16760   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16761
16762   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16763   unsigned FrameReg =
16764       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16765   unsigned SPReg = RegInfo->getStackRegister();
16766   unsigned SlotSize = RegInfo->getSlotSize();
16767
16768   // Get incoming EBP.
16769   SDValue IncomingEBP =
16770       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16771
16772   // SP is saved in the first field of every registration node, so load
16773   // [EBP-RegNodeSize] into SP.
16774   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16775   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16776                                DAG.getConstant(-RegNodeSize, dl, VT));
16777   SDValue NewSP =
16778       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16779                   false, VT.getScalarSizeInBits() / 8);
16780   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16781
16782   if (!RegInfo->needsStackRealignment(MF)) {
16783     // Adjust EBP to point back to the original frame position.
16784     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16785     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16786   } else {
16787     assert(RegInfo->hasBasePointer(MF) &&
16788            "functions with Win32 EH must use frame or base pointer register");
16789
16790     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16791     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16792     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16793
16794     // Reload the spilled EBP value, now that the stack and base pointers are
16795     // set up.
16796     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16797     X86FI->setHasSEHFramePtrSave(true);
16798     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16799     X86FI->setSEHFramePtrSaveIndex(FI);
16800     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16801                                 MachinePointerInfo(), false, false, false,
16802                                 VT.getScalarSizeInBits() / 8);
16803     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16804   }
16805
16806   return Chain;
16807 }
16808
16809 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16810 /// return truncate Store/MaskedStore Node
16811 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16812                                                SelectionDAG &DAG,
16813                                                MVT ElementType) {
16814   SDLoc dl(Op);
16815   SDValue Mask = Op.getOperand(4);
16816   SDValue DataToTruncate = Op.getOperand(3);
16817   SDValue Addr = Op.getOperand(2);
16818   SDValue Chain = Op.getOperand(0);
16819
16820   EVT VT  = DataToTruncate.getValueType();
16821   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16822                              ElementType, VT.getVectorNumElements());
16823
16824   if (isAllOnes(Mask)) // return just a truncate store
16825     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16826                              MachinePointerInfo(), SVT, false, false,
16827                              SVT.getScalarSizeInBits()/8);
16828
16829   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16830                                 MVT::i1, VT.getVectorNumElements());
16831   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16832                                    Mask.getValueType().getSizeInBits());
16833   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16834   // are extracted by EXTRACT_SUBVECTOR.
16835   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16836                               DAG.getBitcast(BitcastVT, Mask),
16837                               DAG.getIntPtrConstant(0, dl));
16838
16839   MachineMemOperand *MMO = DAG.getMachineFunction().
16840     getMachineMemOperand(MachinePointerInfo(),
16841                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16842                          SVT.getScalarSizeInBits()/8);
16843
16844   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16845                             VMask, SVT, MMO, true);
16846 }
16847
16848 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16849                                       SelectionDAG &DAG) {
16850   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16851
16852   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16853   if (!IntrData) {
16854     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16855       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16856     return SDValue();
16857   }
16858
16859   SDLoc dl(Op);
16860   switch(IntrData->Type) {
16861   default:
16862     llvm_unreachable("Unknown Intrinsic Type");
16863     break;
16864   case RDSEED:
16865   case RDRAND: {
16866     // Emit the node with the right value type.
16867     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16868     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16869
16870     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16871     // Otherwise return the value from Rand, which is always 0, casted to i32.
16872     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16873                       DAG.getConstant(1, dl, Op->getValueType(1)),
16874                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16875                       SDValue(Result.getNode(), 1) };
16876     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16877                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16878                                   Ops);
16879
16880     // Return { result, isValid, chain }.
16881     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16882                        SDValue(Result.getNode(), 2));
16883   }
16884   case GATHER: {
16885   //gather(v1, mask, index, base, scale);
16886     SDValue Chain = Op.getOperand(0);
16887     SDValue Src   = Op.getOperand(2);
16888     SDValue Base  = Op.getOperand(3);
16889     SDValue Index = Op.getOperand(4);
16890     SDValue Mask  = Op.getOperand(5);
16891     SDValue Scale = Op.getOperand(6);
16892     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16893                          Chain, Subtarget);
16894   }
16895   case SCATTER: {
16896   //scatter(base, mask, index, v1, scale);
16897     SDValue Chain = Op.getOperand(0);
16898     SDValue Base  = Op.getOperand(2);
16899     SDValue Mask  = Op.getOperand(3);
16900     SDValue Index = Op.getOperand(4);
16901     SDValue Src   = Op.getOperand(5);
16902     SDValue Scale = Op.getOperand(6);
16903     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16904                           Scale, Chain);
16905   }
16906   case PREFETCH: {
16907     SDValue Hint = Op.getOperand(6);
16908     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16909     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16910     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16911     SDValue Chain = Op.getOperand(0);
16912     SDValue Mask  = Op.getOperand(2);
16913     SDValue Index = Op.getOperand(3);
16914     SDValue Base  = Op.getOperand(4);
16915     SDValue Scale = Op.getOperand(5);
16916     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16917   }
16918   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16919   case RDTSC: {
16920     SmallVector<SDValue, 2> Results;
16921     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16922                             Results);
16923     return DAG.getMergeValues(Results, dl);
16924   }
16925   // Read Performance Monitoring Counters.
16926   case RDPMC: {
16927     SmallVector<SDValue, 2> Results;
16928     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16929     return DAG.getMergeValues(Results, dl);
16930   }
16931   // XTEST intrinsics.
16932   case XTEST: {
16933     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16934     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16935     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16936                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16937                                 InTrans);
16938     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16939     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16940                        Ret, SDValue(InTrans.getNode(), 1));
16941   }
16942   // ADC/ADCX/SBB
16943   case ADX: {
16944     SmallVector<SDValue, 2> Results;
16945     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16946     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16947     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16948                                 DAG.getConstant(-1, dl, MVT::i8));
16949     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16950                               Op.getOperand(4), GenCF.getValue(1));
16951     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16952                                  Op.getOperand(5), MachinePointerInfo(),
16953                                  false, false, 0);
16954     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16955                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16956                                 Res.getValue(1));
16957     Results.push_back(SetCC);
16958     Results.push_back(Store);
16959     return DAG.getMergeValues(Results, dl);
16960   }
16961   case COMPRESS_TO_MEM: {
16962     SDLoc dl(Op);
16963     SDValue Mask = Op.getOperand(4);
16964     SDValue DataToCompress = Op.getOperand(3);
16965     SDValue Addr = Op.getOperand(2);
16966     SDValue Chain = Op.getOperand(0);
16967
16968     EVT VT = DataToCompress.getValueType();
16969     if (isAllOnes(Mask)) // return just a store
16970       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16971                           MachinePointerInfo(), false, false,
16972                           VT.getScalarSizeInBits()/8);
16973
16974     SDValue Compressed =
16975       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16976                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16977     return DAG.getStore(Chain, dl, Compressed, Addr,
16978                         MachinePointerInfo(), false, false,
16979                         VT.getScalarSizeInBits()/8);
16980   }
16981   case TRUNCATE_TO_MEM_VI8:
16982     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16983   case TRUNCATE_TO_MEM_VI16:
16984     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16985   case TRUNCATE_TO_MEM_VI32:
16986     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16987   case EXPAND_FROM_MEM: {
16988     SDLoc dl(Op);
16989     SDValue Mask = Op.getOperand(4);
16990     SDValue PassThru = Op.getOperand(3);
16991     SDValue Addr = Op.getOperand(2);
16992     SDValue Chain = Op.getOperand(0);
16993     EVT VT = Op.getValueType();
16994
16995     if (isAllOnes(Mask)) // return just a load
16996       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16997                          false, VT.getScalarSizeInBits()/8);
16998
16999     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17000                                        false, false, false,
17001                                        VT.getScalarSizeInBits()/8);
17002
17003     SDValue Results[] = {
17004       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17005                            Mask, PassThru, Subtarget, DAG), Chain};
17006     return DAG.getMergeValues(Results, dl);
17007   }
17008   }
17009 }
17010
17011 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17012                                            SelectionDAG &DAG) const {
17013   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17014   MFI->setReturnAddressIsTaken(true);
17015
17016   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17017     return SDValue();
17018
17019   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17020   SDLoc dl(Op);
17021   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17022
17023   if (Depth > 0) {
17024     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17025     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17026     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17027     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17028                        DAG.getNode(ISD::ADD, dl, PtrVT,
17029                                    FrameAddr, Offset),
17030                        MachinePointerInfo(), false, false, false, 0);
17031   }
17032
17033   // Just load the return address.
17034   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17035   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17036                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17037 }
17038
17039 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17040   MachineFunction &MF = DAG.getMachineFunction();
17041   MachineFrameInfo *MFI = MF.getFrameInfo();
17042   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17043   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17044   EVT VT = Op.getValueType();
17045
17046   MFI->setFrameAddressIsTaken(true);
17047
17048   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17049     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17050     // is not possible to crawl up the stack without looking at the unwind codes
17051     // simultaneously.
17052     int FrameAddrIndex = FuncInfo->getFAIndex();
17053     if (!FrameAddrIndex) {
17054       // Set up a frame object for the return address.
17055       unsigned SlotSize = RegInfo->getSlotSize();
17056       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17057           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17058       FuncInfo->setFAIndex(FrameAddrIndex);
17059     }
17060     return DAG.getFrameIndex(FrameAddrIndex, VT);
17061   }
17062
17063   unsigned FrameReg =
17064       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17065   SDLoc dl(Op);  // FIXME probably not meaningful
17066   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17067   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17068           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17069          "Invalid Frame Register!");
17070   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17071   while (Depth--)
17072     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17073                             MachinePointerInfo(),
17074                             false, false, false, 0);
17075   return FrameAddr;
17076 }
17077
17078 // FIXME? Maybe this could be a TableGen attribute on some registers and
17079 // this table could be generated automatically from RegInfo.
17080 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17081                                               SelectionDAG &DAG) const {
17082   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17083   const MachineFunction &MF = DAG.getMachineFunction();
17084
17085   unsigned Reg = StringSwitch<unsigned>(RegName)
17086                        .Case("esp", X86::ESP)
17087                        .Case("rsp", X86::RSP)
17088                        .Case("ebp", X86::EBP)
17089                        .Case("rbp", X86::RBP)
17090                        .Default(0);
17091
17092   if (Reg == X86::EBP || Reg == X86::RBP) {
17093     if (!TFI.hasFP(MF))
17094       report_fatal_error("register " + StringRef(RegName) +
17095                          " is allocatable: function has no frame pointer");
17096 #ifndef NDEBUG
17097     else {
17098       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17099       unsigned FrameReg =
17100           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17101       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17102              "Invalid Frame Register!");
17103     }
17104 #endif
17105   }
17106
17107   if (Reg)
17108     return Reg;
17109
17110   report_fatal_error("Invalid register name global variable");
17111 }
17112
17113 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17114                                                      SelectionDAG &DAG) const {
17115   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17116   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17117 }
17118
17119 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17120   SDValue Chain     = Op.getOperand(0);
17121   SDValue Offset    = Op.getOperand(1);
17122   SDValue Handler   = Op.getOperand(2);
17123   SDLoc dl      (Op);
17124
17125   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17126   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17127   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17128   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17129           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17130          "Invalid Frame Register!");
17131   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17132   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17133
17134   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17135                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17136                                                        dl));
17137   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17138   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17139                        false, false, 0);
17140   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17141
17142   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17143                      DAG.getRegister(StoreAddrReg, PtrVT));
17144 }
17145
17146 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17147                                                SelectionDAG &DAG) const {
17148   SDLoc DL(Op);
17149   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17150                      DAG.getVTList(MVT::i32, MVT::Other),
17151                      Op.getOperand(0), Op.getOperand(1));
17152 }
17153
17154 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17155                                                 SelectionDAG &DAG) const {
17156   SDLoc DL(Op);
17157   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17158                      Op.getOperand(0), Op.getOperand(1));
17159 }
17160
17161 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17162   return Op.getOperand(0);
17163 }
17164
17165 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17166                                                 SelectionDAG &DAG) const {
17167   SDValue Root = Op.getOperand(0);
17168   SDValue Trmp = Op.getOperand(1); // trampoline
17169   SDValue FPtr = Op.getOperand(2); // nested function
17170   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17171   SDLoc dl (Op);
17172
17173   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17174   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17175
17176   if (Subtarget->is64Bit()) {
17177     SDValue OutChains[6];
17178
17179     // Large code-model.
17180     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17181     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17182
17183     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17184     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17185
17186     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17187
17188     // Load the pointer to the nested function into R11.
17189     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17190     SDValue Addr = Trmp;
17191     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17192                                 Addr, MachinePointerInfo(TrmpAddr),
17193                                 false, false, 0);
17194
17195     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17196                        DAG.getConstant(2, dl, MVT::i64));
17197     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17198                                 MachinePointerInfo(TrmpAddr, 2),
17199                                 false, false, 2);
17200
17201     // Load the 'nest' parameter value into R10.
17202     // R10 is specified in X86CallingConv.td
17203     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17204     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17205                        DAG.getConstant(10, dl, MVT::i64));
17206     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17207                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17208                                 false, false, 0);
17209
17210     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17211                        DAG.getConstant(12, dl, MVT::i64));
17212     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17213                                 MachinePointerInfo(TrmpAddr, 12),
17214                                 false, false, 2);
17215
17216     // Jump to the nested function.
17217     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17218     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17219                        DAG.getConstant(20, dl, MVT::i64));
17220     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17221                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17222                                 false, false, 0);
17223
17224     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17225     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17226                        DAG.getConstant(22, dl, MVT::i64));
17227     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17228                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17229                                 false, false, 0);
17230
17231     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17232   } else {
17233     const Function *Func =
17234       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17235     CallingConv::ID CC = Func->getCallingConv();
17236     unsigned NestReg;
17237
17238     switch (CC) {
17239     default:
17240       llvm_unreachable("Unsupported calling convention");
17241     case CallingConv::C:
17242     case CallingConv::X86_StdCall: {
17243       // Pass 'nest' parameter in ECX.
17244       // Must be kept in sync with X86CallingConv.td
17245       NestReg = X86::ECX;
17246
17247       // Check that ECX wasn't needed by an 'inreg' parameter.
17248       FunctionType *FTy = Func->getFunctionType();
17249       const AttributeSet &Attrs = Func->getAttributes();
17250
17251       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17252         unsigned InRegCount = 0;
17253         unsigned Idx = 1;
17254
17255         for (FunctionType::param_iterator I = FTy->param_begin(),
17256              E = FTy->param_end(); I != E; ++I, ++Idx)
17257           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17258             auto &DL = DAG.getDataLayout();
17259             // FIXME: should only count parameters that are lowered to integers.
17260             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17261           }
17262
17263         if (InRegCount > 2) {
17264           report_fatal_error("Nest register in use - reduce number of inreg"
17265                              " parameters!");
17266         }
17267       }
17268       break;
17269     }
17270     case CallingConv::X86_FastCall:
17271     case CallingConv::X86_ThisCall:
17272     case CallingConv::Fast:
17273       // Pass 'nest' parameter in EAX.
17274       // Must be kept in sync with X86CallingConv.td
17275       NestReg = X86::EAX;
17276       break;
17277     }
17278
17279     SDValue OutChains[4];
17280     SDValue Addr, Disp;
17281
17282     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17283                        DAG.getConstant(10, dl, MVT::i32));
17284     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17285
17286     // This is storing the opcode for MOV32ri.
17287     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17288     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17289     OutChains[0] = DAG.getStore(Root, dl,
17290                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17291                                 Trmp, MachinePointerInfo(TrmpAddr),
17292                                 false, false, 0);
17293
17294     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17295                        DAG.getConstant(1, dl, MVT::i32));
17296     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17297                                 MachinePointerInfo(TrmpAddr, 1),
17298                                 false, false, 1);
17299
17300     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17301     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17302                        DAG.getConstant(5, dl, MVT::i32));
17303     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17304                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17305                                 false, false, 1);
17306
17307     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17308                        DAG.getConstant(6, dl, MVT::i32));
17309     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17310                                 MachinePointerInfo(TrmpAddr, 6),
17311                                 false, false, 1);
17312
17313     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17314   }
17315 }
17316
17317 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17318                                             SelectionDAG &DAG) const {
17319   /*
17320    The rounding mode is in bits 11:10 of FPSR, and has the following
17321    settings:
17322      00 Round to nearest
17323      01 Round to -inf
17324      10 Round to +inf
17325      11 Round to 0
17326
17327   FLT_ROUNDS, on the other hand, expects the following:
17328     -1 Undefined
17329      0 Round to 0
17330      1 Round to nearest
17331      2 Round to +inf
17332      3 Round to -inf
17333
17334   To perform the conversion, we do:
17335     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17336   */
17337
17338   MachineFunction &MF = DAG.getMachineFunction();
17339   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17340   unsigned StackAlignment = TFI.getStackAlignment();
17341   MVT VT = Op.getSimpleValueType();
17342   SDLoc DL(Op);
17343
17344   // Save FP Control Word to stack slot
17345   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17346   SDValue StackSlot =
17347       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17348
17349   MachineMemOperand *MMO =
17350       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17351                               MachineMemOperand::MOStore, 2, 2);
17352
17353   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17354   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17355                                           DAG.getVTList(MVT::Other),
17356                                           Ops, MVT::i16, MMO);
17357
17358   // Load FP Control Word from stack slot
17359   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17360                             MachinePointerInfo(), false, false, false, 0);
17361
17362   // Transform as necessary
17363   SDValue CWD1 =
17364     DAG.getNode(ISD::SRL, DL, MVT::i16,
17365                 DAG.getNode(ISD::AND, DL, MVT::i16,
17366                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17367                 DAG.getConstant(11, DL, MVT::i8));
17368   SDValue CWD2 =
17369     DAG.getNode(ISD::SRL, DL, MVT::i16,
17370                 DAG.getNode(ISD::AND, DL, MVT::i16,
17371                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17372                 DAG.getConstant(9, DL, MVT::i8));
17373
17374   SDValue RetVal =
17375     DAG.getNode(ISD::AND, DL, MVT::i16,
17376                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17377                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17378                             DAG.getConstant(1, DL, MVT::i16)),
17379                 DAG.getConstant(3, DL, MVT::i16));
17380
17381   return DAG.getNode((VT.getSizeInBits() < 16 ?
17382                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17383 }
17384
17385 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17386   MVT VT = Op.getSimpleValueType();
17387   EVT OpVT = VT;
17388   unsigned NumBits = VT.getSizeInBits();
17389   SDLoc dl(Op);
17390
17391   Op = Op.getOperand(0);
17392   if (VT == MVT::i8) {
17393     // Zero extend to i32 since there is not an i8 bsr.
17394     OpVT = MVT::i32;
17395     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17396   }
17397
17398   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17399   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17400   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17401
17402   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17403   SDValue Ops[] = {
17404     Op,
17405     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17406     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17407     Op.getValue(1)
17408   };
17409   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17410
17411   // Finally xor with NumBits-1.
17412   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17413                    DAG.getConstant(NumBits - 1, dl, OpVT));
17414
17415   if (VT == MVT::i8)
17416     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17417   return Op;
17418 }
17419
17420 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17421   MVT VT = Op.getSimpleValueType();
17422   EVT OpVT = VT;
17423   unsigned NumBits = VT.getSizeInBits();
17424   SDLoc dl(Op);
17425
17426   Op = Op.getOperand(0);
17427   if (VT == MVT::i8) {
17428     // Zero extend to i32 since there is not an i8 bsr.
17429     OpVT = MVT::i32;
17430     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17431   }
17432
17433   // Issue a bsr (scan bits in reverse).
17434   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17435   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17436
17437   // And xor with NumBits-1.
17438   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17439                    DAG.getConstant(NumBits - 1, dl, OpVT));
17440
17441   if (VT == MVT::i8)
17442     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17443   return Op;
17444 }
17445
17446 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17447   MVT VT = Op.getSimpleValueType();
17448   unsigned NumBits = VT.getScalarSizeInBits();
17449   SDLoc dl(Op);
17450
17451   if (VT.isVector()) {
17452     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17453
17454     SDValue N0 = Op.getOperand(0);
17455     SDValue Zero = DAG.getConstant(0, dl, VT);
17456
17457     // lsb(x) = (x & -x)
17458     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17459                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17460
17461     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17462     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17463         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17464       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17465       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17466                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17467     }
17468
17469     // cttz(x) = ctpop(lsb - 1)
17470     SDValue One = DAG.getConstant(1, dl, VT);
17471     return DAG.getNode(ISD::CTPOP, dl, VT,
17472                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17473   }
17474
17475   assert(Op.getOpcode() == ISD::CTTZ &&
17476          "Only scalar CTTZ requires custom lowering");
17477
17478   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17479   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17480   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17481
17482   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17483   SDValue Ops[] = {
17484     Op,
17485     DAG.getConstant(NumBits, dl, VT),
17486     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17487     Op.getValue(1)
17488   };
17489   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17490 }
17491
17492 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17493 // ones, and then concatenate the result back.
17494 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17495   MVT VT = Op.getSimpleValueType();
17496
17497   assert(VT.is256BitVector() && VT.isInteger() &&
17498          "Unsupported value type for operation");
17499
17500   unsigned NumElems = VT.getVectorNumElements();
17501   SDLoc dl(Op);
17502
17503   // Extract the LHS vectors
17504   SDValue LHS = Op.getOperand(0);
17505   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17506   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17507
17508   // Extract the RHS vectors
17509   SDValue RHS = Op.getOperand(1);
17510   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17511   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17512
17513   MVT EltVT = VT.getVectorElementType();
17514   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17515
17516   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17517                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17518                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17519 }
17520
17521 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17522   if (Op.getValueType() == MVT::i1)
17523     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17524                        Op.getOperand(0), Op.getOperand(1));
17525   assert(Op.getSimpleValueType().is256BitVector() &&
17526          Op.getSimpleValueType().isInteger() &&
17527          "Only handle AVX 256-bit vector integer operation");
17528   return Lower256IntArith(Op, DAG);
17529 }
17530
17531 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17532   if (Op.getValueType() == MVT::i1)
17533     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17534                        Op.getOperand(0), Op.getOperand(1));
17535   assert(Op.getSimpleValueType().is256BitVector() &&
17536          Op.getSimpleValueType().isInteger() &&
17537          "Only handle AVX 256-bit vector integer operation");
17538   return Lower256IntArith(Op, DAG);
17539 }
17540
17541 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17542   assert(Op.getSimpleValueType().is256BitVector() &&
17543          Op.getSimpleValueType().isInteger() &&
17544          "Only handle AVX 256-bit vector integer operation");
17545   return Lower256IntArith(Op, DAG);
17546 }
17547
17548 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17549                         SelectionDAG &DAG) {
17550   SDLoc dl(Op);
17551   MVT VT = Op.getSimpleValueType();
17552
17553   if (VT == MVT::i1)
17554     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17555
17556   // Decompose 256-bit ops into smaller 128-bit ops.
17557   if (VT.is256BitVector() && !Subtarget->hasInt256())
17558     return Lower256IntArith(Op, DAG);
17559
17560   SDValue A = Op.getOperand(0);
17561   SDValue B = Op.getOperand(1);
17562
17563   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17564   // pairs, multiply and truncate.
17565   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17566     if (Subtarget->hasInt256()) {
17567       if (VT == MVT::v32i8) {
17568         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17569         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17570         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17571         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17572         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17573         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17574         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17575         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17576                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17577                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17578       }
17579
17580       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17581       return DAG.getNode(
17582           ISD::TRUNCATE, dl, VT,
17583           DAG.getNode(ISD::MUL, dl, ExVT,
17584                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17585                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17586     }
17587
17588     assert(VT == MVT::v16i8 &&
17589            "Pre-AVX2 support only supports v16i8 multiplication");
17590     MVT ExVT = MVT::v8i16;
17591
17592     // Extract the lo parts and sign extend to i16
17593     SDValue ALo, BLo;
17594     if (Subtarget->hasSSE41()) {
17595       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17596       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17597     } else {
17598       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17599                               -1, 4, -1, 5, -1, 6, -1, 7};
17600       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17601       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17602       ALo = DAG.getBitcast(ExVT, ALo);
17603       BLo = DAG.getBitcast(ExVT, BLo);
17604       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17605       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17606     }
17607
17608     // Extract the hi parts and sign extend to i16
17609     SDValue AHi, BHi;
17610     if (Subtarget->hasSSE41()) {
17611       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17612                               -1, -1, -1, -1, -1, -1, -1, -1};
17613       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17614       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17615       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17616       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17617     } else {
17618       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17619                               -1, 12, -1, 13, -1, 14, -1, 15};
17620       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17621       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17622       AHi = DAG.getBitcast(ExVT, AHi);
17623       BHi = DAG.getBitcast(ExVT, BHi);
17624       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17625       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17626     }
17627
17628     // Multiply, mask the lower 8bits of the lo/hi results and pack
17629     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17630     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17631     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17632     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17633     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17634   }
17635
17636   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17637   if (VT == MVT::v4i32) {
17638     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17639            "Should not custom lower when pmuldq is available!");
17640
17641     // Extract the odd parts.
17642     static const int UnpackMask[] = { 1, -1, 3, -1 };
17643     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17644     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17645
17646     // Multiply the even parts.
17647     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17648     // Now multiply odd parts.
17649     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17650
17651     Evens = DAG.getBitcast(VT, Evens);
17652     Odds = DAG.getBitcast(VT, Odds);
17653
17654     // Merge the two vectors back together with a shuffle. This expands into 2
17655     // shuffles.
17656     static const int ShufMask[] = { 0, 4, 2, 6 };
17657     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17658   }
17659
17660   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17661          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17662
17663   //  Ahi = psrlqi(a, 32);
17664   //  Bhi = psrlqi(b, 32);
17665   //
17666   //  AloBlo = pmuludq(a, b);
17667   //  AloBhi = pmuludq(a, Bhi);
17668   //  AhiBlo = pmuludq(Ahi, b);
17669
17670   //  AloBhi = psllqi(AloBhi, 32);
17671   //  AhiBlo = psllqi(AhiBlo, 32);
17672   //  return AloBlo + AloBhi + AhiBlo;
17673
17674   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17675   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17676
17677   SDValue AhiBlo = Ahi;
17678   SDValue AloBhi = Bhi;
17679   // Bit cast to 32-bit vectors for MULUDQ
17680   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17681                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17682   A = DAG.getBitcast(MulVT, A);
17683   B = DAG.getBitcast(MulVT, B);
17684   Ahi = DAG.getBitcast(MulVT, Ahi);
17685   Bhi = DAG.getBitcast(MulVT, Bhi);
17686
17687   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17688   // After shifting right const values the result may be all-zero.
17689   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17690     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17691     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17692   }
17693   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17694     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17695     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17696   }
17697
17698   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17699   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17700 }
17701
17702 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17703   assert(Subtarget->isTargetWin64() && "Unexpected target");
17704   EVT VT = Op.getValueType();
17705   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17706          "Unexpected return type for lowering");
17707
17708   RTLIB::Libcall LC;
17709   bool isSigned;
17710   switch (Op->getOpcode()) {
17711   default: llvm_unreachable("Unexpected request for libcall!");
17712   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17713   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17714   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17715   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17716   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17717   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17718   }
17719
17720   SDLoc dl(Op);
17721   SDValue InChain = DAG.getEntryNode();
17722
17723   TargetLowering::ArgListTy Args;
17724   TargetLowering::ArgListEntry Entry;
17725   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17726     EVT ArgVT = Op->getOperand(i).getValueType();
17727     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17728            "Unexpected argument type for lowering");
17729     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17730     Entry.Node = StackPtr;
17731     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17732                            false, false, 16);
17733     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17734     Entry.Ty = PointerType::get(ArgTy,0);
17735     Entry.isSExt = false;
17736     Entry.isZExt = false;
17737     Args.push_back(Entry);
17738   }
17739
17740   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17741                                          getPointerTy(DAG.getDataLayout()));
17742
17743   TargetLowering::CallLoweringInfo CLI(DAG);
17744   CLI.setDebugLoc(dl).setChain(InChain)
17745     .setCallee(getLibcallCallingConv(LC),
17746                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17747                Callee, std::move(Args), 0)
17748     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17749
17750   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17751   return DAG.getBitcast(VT, CallInfo.first);
17752 }
17753
17754 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17755                              SelectionDAG &DAG) {
17756   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17757   EVT VT = Op0.getValueType();
17758   SDLoc dl(Op);
17759
17760   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17761          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17762
17763   // PMULxD operations multiply each even value (starting at 0) of LHS with
17764   // the related value of RHS and produce a widen result.
17765   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17766   // => <2 x i64> <ae|cg>
17767   //
17768   // In other word, to have all the results, we need to perform two PMULxD:
17769   // 1. one with the even values.
17770   // 2. one with the odd values.
17771   // To achieve #2, with need to place the odd values at an even position.
17772   //
17773   // Place the odd value at an even position (basically, shift all values 1
17774   // step to the left):
17775   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17776   // <a|b|c|d> => <b|undef|d|undef>
17777   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17778   // <e|f|g|h> => <f|undef|h|undef>
17779   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17780
17781   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17782   // ints.
17783   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17784   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17785   unsigned Opcode =
17786       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17787   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17788   // => <2 x i64> <ae|cg>
17789   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17790   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17791   // => <2 x i64> <bf|dh>
17792   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17793
17794   // Shuffle it back into the right order.
17795   SDValue Highs, Lows;
17796   if (VT == MVT::v8i32) {
17797     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17798     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17799     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17800     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17801   } else {
17802     const int HighMask[] = {1, 5, 3, 7};
17803     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17804     const int LowMask[] = {0, 4, 2, 6};
17805     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17806   }
17807
17808   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17809   // unsigned multiply.
17810   if (IsSigned && !Subtarget->hasSSE41()) {
17811     SDValue ShAmt = DAG.getConstant(
17812         31, dl,
17813         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17814     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17815                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17816     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17817                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17818
17819     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17820     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17821   }
17822
17823   // The first result of MUL_LOHI is actually the low value, followed by the
17824   // high value.
17825   SDValue Ops[] = {Lows, Highs};
17826   return DAG.getMergeValues(Ops, dl);
17827 }
17828
17829 // Return true if the required (according to Opcode) shift-imm form is natively
17830 // supported by the Subtarget
17831 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17832                                         unsigned Opcode) {
17833   if (VT.getScalarSizeInBits() < 16)
17834     return false;
17835
17836   if (VT.is512BitVector() &&
17837       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17838     return true;
17839
17840   bool LShift = VT.is128BitVector() ||
17841     (VT.is256BitVector() && Subtarget->hasInt256());
17842
17843   bool AShift = LShift && (Subtarget->hasVLX() ||
17844     (VT != MVT::v2i64 && VT != MVT::v4i64));
17845   return (Opcode == ISD::SRA) ? AShift : LShift;
17846 }
17847
17848 // The shift amount is a variable, but it is the same for all vector lanes.
17849 // These instructions are defined together with shift-immediate.
17850 static
17851 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17852                                       unsigned Opcode) {
17853   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17854 }
17855
17856 // Return true if the required (according to Opcode) variable-shift form is
17857 // natively supported by the Subtarget
17858 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17859                                     unsigned Opcode) {
17860
17861   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17862     return false;
17863
17864   // vXi16 supported only on AVX-512, BWI
17865   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17866     return false;
17867
17868   if (VT.is512BitVector() || Subtarget->hasVLX())
17869     return true;
17870
17871   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17872   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17873   return (Opcode == ISD::SRA) ? AShift : LShift;
17874 }
17875
17876 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17877                                          const X86Subtarget *Subtarget) {
17878   MVT VT = Op.getSimpleValueType();
17879   SDLoc dl(Op);
17880   SDValue R = Op.getOperand(0);
17881   SDValue Amt = Op.getOperand(1);
17882
17883   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17884     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17885
17886   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17887     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17888     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17889     SDValue Ex = DAG.getBitcast(ExVT, R);
17890
17891     if (ShiftAmt >= 32) {
17892       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17893       SDValue Upper =
17894           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17895       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17896                                                  ShiftAmt - 32, DAG);
17897       if (VT == MVT::v2i64)
17898         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17899       if (VT == MVT::v4i64)
17900         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17901                                   {9, 1, 11, 3, 13, 5, 15, 7});
17902     } else {
17903       // SRA upper i32, SHL whole i64 and select lower i32.
17904       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17905                                                  ShiftAmt, DAG);
17906       SDValue Lower =
17907           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17908       Lower = DAG.getBitcast(ExVT, Lower);
17909       if (VT == MVT::v2i64)
17910         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17911       if (VT == MVT::v4i64)
17912         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17913                                   {8, 1, 10, 3, 12, 5, 14, 7});
17914     }
17915     return DAG.getBitcast(VT, Ex);
17916   };
17917
17918   // Optimize shl/srl/sra with constant shift amount.
17919   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17920     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17921       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17922
17923       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17924         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17925
17926       // i64 SRA needs to be performed as partial shifts.
17927       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17928           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
17929         return ArithmeticShiftRight64(ShiftAmt);
17930
17931       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17932         unsigned NumElts = VT.getVectorNumElements();
17933         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17934
17935         // Simple i8 add case
17936         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
17937           return DAG.getNode(ISD::ADD, dl, VT, R, R);
17938
17939         // ashr(R, 7)  === cmp_slt(R, 0)
17940         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
17941           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17942           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17943         }
17944
17945         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
17946         if (VT == MVT::v16i8 && Subtarget->hasXOP())
17947           return SDValue();
17948
17949         if (Op.getOpcode() == ISD::SHL) {
17950           // Make a large shift.
17951           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17952                                                    R, ShiftAmt, DAG);
17953           SHL = DAG.getBitcast(VT, SHL);
17954           // Zero out the rightmost bits.
17955           SmallVector<SDValue, 32> V(
17956               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17957           return DAG.getNode(ISD::AND, dl, VT, SHL,
17958                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17959         }
17960         if (Op.getOpcode() == ISD::SRL) {
17961           // Make a large shift.
17962           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17963                                                    R, ShiftAmt, DAG);
17964           SRL = DAG.getBitcast(VT, SRL);
17965           // Zero out the leftmost bits.
17966           SmallVector<SDValue, 32> V(
17967               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17968           return DAG.getNode(ISD::AND, dl, VT, SRL,
17969                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17970         }
17971         if (Op.getOpcode() == ISD::SRA) {
17972           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17973           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17974           SmallVector<SDValue, 32> V(NumElts,
17975                                      DAG.getConstant(128 >> ShiftAmt, dl,
17976                                                      MVT::i8));
17977           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17978           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17979           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17980           return Res;
17981         }
17982         llvm_unreachable("Unknown shift opcode.");
17983       }
17984     }
17985   }
17986
17987   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17988   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
17989       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17990
17991     // Peek through any splat that was introduced for i64 shift vectorization.
17992     int SplatIndex = -1;
17993     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17994       if (SVN->isSplat()) {
17995         SplatIndex = SVN->getSplatIndex();
17996         Amt = Amt.getOperand(0);
17997         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17998                "Splat shuffle referencing second operand");
17999       }
18000
18001     if (Amt.getOpcode() != ISD::BITCAST ||
18002         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18003       return SDValue();
18004
18005     Amt = Amt.getOperand(0);
18006     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18007                      VT.getVectorNumElements();
18008     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18009     uint64_t ShiftAmt = 0;
18010     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18011     for (unsigned i = 0; i != Ratio; ++i) {
18012       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18013       if (!C)
18014         return SDValue();
18015       // 6 == Log2(64)
18016       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18017     }
18018
18019     // Check remaining shift amounts (if not a splat).
18020     if (SplatIndex < 0) {
18021       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18022         uint64_t ShAmt = 0;
18023         for (unsigned j = 0; j != Ratio; ++j) {
18024           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18025           if (!C)
18026             return SDValue();
18027           // 6 == Log2(64)
18028           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18029         }
18030         if (ShAmt != ShiftAmt)
18031           return SDValue();
18032       }
18033     }
18034
18035     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18036       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18037
18038     if (Op.getOpcode() == ISD::SRA)
18039       return ArithmeticShiftRight64(ShiftAmt);
18040   }
18041
18042   return SDValue();
18043 }
18044
18045 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18046                                         const X86Subtarget* Subtarget) {
18047   MVT VT = Op.getSimpleValueType();
18048   SDLoc dl(Op);
18049   SDValue R = Op.getOperand(0);
18050   SDValue Amt = Op.getOperand(1);
18051
18052   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18053     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18054
18055   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18056     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18057
18058   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18059     SDValue BaseShAmt;
18060     EVT EltVT = VT.getVectorElementType();
18061
18062     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18063       // Check if this build_vector node is doing a splat.
18064       // If so, then set BaseShAmt equal to the splat value.
18065       BaseShAmt = BV->getSplatValue();
18066       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18067         BaseShAmt = SDValue();
18068     } else {
18069       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18070         Amt = Amt.getOperand(0);
18071
18072       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18073       if (SVN && SVN->isSplat()) {
18074         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18075         SDValue InVec = Amt.getOperand(0);
18076         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18077           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18078                  "Unexpected shuffle index found!");
18079           BaseShAmt = InVec.getOperand(SplatIdx);
18080         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18081            if (ConstantSDNode *C =
18082                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18083              if (C->getZExtValue() == SplatIdx)
18084                BaseShAmt = InVec.getOperand(1);
18085            }
18086         }
18087
18088         if (!BaseShAmt)
18089           // Avoid introducing an extract element from a shuffle.
18090           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18091                                   DAG.getIntPtrConstant(SplatIdx, dl));
18092       }
18093     }
18094
18095     if (BaseShAmt.getNode()) {
18096       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18097       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18098         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18099       else if (EltVT.bitsLT(MVT::i32))
18100         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18101
18102       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18103     }
18104   }
18105
18106   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18107   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18108       Amt.getOpcode() == ISD::BITCAST &&
18109       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18110     Amt = Amt.getOperand(0);
18111     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18112                      VT.getVectorNumElements();
18113     std::vector<SDValue> Vals(Ratio);
18114     for (unsigned i = 0; i != Ratio; ++i)
18115       Vals[i] = Amt.getOperand(i);
18116     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18117       for (unsigned j = 0; j != Ratio; ++j)
18118         if (Vals[j] != Amt.getOperand(i + j))
18119           return SDValue();
18120     }
18121
18122     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18123       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18124   }
18125   return SDValue();
18126 }
18127
18128 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18129                           SelectionDAG &DAG) {
18130   MVT VT = Op.getSimpleValueType();
18131   SDLoc dl(Op);
18132   SDValue R = Op.getOperand(0);
18133   SDValue Amt = Op.getOperand(1);
18134
18135   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18136   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18137
18138   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18139     return V;
18140
18141   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18142     return V;
18143
18144   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18145     return Op;
18146
18147   // XOP has 128-bit variable logical/arithmetic shifts.
18148   // +ve/-ve Amt = shift left/right.
18149   if (Subtarget->hasXOP() &&
18150       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18151        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18152     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18153       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18154       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18155     }
18156     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18157       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18158     if (Op.getOpcode() == ISD::SRA)
18159       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18160   }
18161
18162   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18163   // shifts per-lane and then shuffle the partial results back together.
18164   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18165     // Splat the shift amounts so the scalar shifts above will catch it.
18166     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18167     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18168     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18169     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18170     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18171   }
18172
18173   // i64 vector arithmetic shift can be emulated with the transform:
18174   // M = lshr(SIGN_BIT, Amt)
18175   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18176   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18177       Op.getOpcode() == ISD::SRA) {
18178     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18179     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18180     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18181     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18182     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18183     return R;
18184   }
18185
18186   // If possible, lower this packed shift into a vector multiply instead of
18187   // expanding it into a sequence of scalar shifts.
18188   // Do this only if the vector shift count is a constant build_vector.
18189   if (Op.getOpcode() == ISD::SHL &&
18190       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18191        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18192       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18193     SmallVector<SDValue, 8> Elts;
18194     EVT SVT = VT.getScalarType();
18195     unsigned SVTBits = SVT.getSizeInBits();
18196     const APInt &One = APInt(SVTBits, 1);
18197     unsigned NumElems = VT.getVectorNumElements();
18198
18199     for (unsigned i=0; i !=NumElems; ++i) {
18200       SDValue Op = Amt->getOperand(i);
18201       if (Op->getOpcode() == ISD::UNDEF) {
18202         Elts.push_back(Op);
18203         continue;
18204       }
18205
18206       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18207       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18208       uint64_t ShAmt = C.getZExtValue();
18209       if (ShAmt >= SVTBits) {
18210         Elts.push_back(DAG.getUNDEF(SVT));
18211         continue;
18212       }
18213       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18214     }
18215     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18216     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18217   }
18218
18219   // Lower SHL with variable shift amount.
18220   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18221     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18222
18223     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18224                      DAG.getConstant(0x3f800000U, dl, VT));
18225     Op = DAG.getBitcast(MVT::v4f32, Op);
18226     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18227     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18228   }
18229
18230   // If possible, lower this shift as a sequence of two shifts by
18231   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18232   // Example:
18233   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18234   //
18235   // Could be rewritten as:
18236   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18237   //
18238   // The advantage is that the two shifts from the example would be
18239   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18240   // the vector shift into four scalar shifts plus four pairs of vector
18241   // insert/extract.
18242   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18243       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18244     unsigned TargetOpcode = X86ISD::MOVSS;
18245     bool CanBeSimplified;
18246     // The splat value for the first packed shift (the 'X' from the example).
18247     SDValue Amt1 = Amt->getOperand(0);
18248     // The splat value for the second packed shift (the 'Y' from the example).
18249     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18250                                         Amt->getOperand(2);
18251
18252     // See if it is possible to replace this node with a sequence of
18253     // two shifts followed by a MOVSS/MOVSD
18254     if (VT == MVT::v4i32) {
18255       // Check if it is legal to use a MOVSS.
18256       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18257                         Amt2 == Amt->getOperand(3);
18258       if (!CanBeSimplified) {
18259         // Otherwise, check if we can still simplify this node using a MOVSD.
18260         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18261                           Amt->getOperand(2) == Amt->getOperand(3);
18262         TargetOpcode = X86ISD::MOVSD;
18263         Amt2 = Amt->getOperand(2);
18264       }
18265     } else {
18266       // Do similar checks for the case where the machine value type
18267       // is MVT::v8i16.
18268       CanBeSimplified = Amt1 == Amt->getOperand(1);
18269       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18270         CanBeSimplified = Amt2 == Amt->getOperand(i);
18271
18272       if (!CanBeSimplified) {
18273         TargetOpcode = X86ISD::MOVSD;
18274         CanBeSimplified = true;
18275         Amt2 = Amt->getOperand(4);
18276         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18277           CanBeSimplified = Amt1 == Amt->getOperand(i);
18278         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18279           CanBeSimplified = Amt2 == Amt->getOperand(j);
18280       }
18281     }
18282
18283     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18284         isa<ConstantSDNode>(Amt2)) {
18285       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18286       EVT CastVT = MVT::v4i32;
18287       SDValue Splat1 =
18288         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18289       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18290       SDValue Splat2 =
18291         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18292       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18293       if (TargetOpcode == X86ISD::MOVSD)
18294         CastVT = MVT::v2i64;
18295       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18296       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18297       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18298                                             BitCast1, DAG);
18299       return DAG.getBitcast(VT, Result);
18300     }
18301   }
18302
18303   // v4i32 Non Uniform Shifts.
18304   // If the shift amount is constant we can shift each lane using the SSE2
18305   // immediate shifts, else we need to zero-extend each lane to the lower i64
18306   // and shift using the SSE2 variable shifts.
18307   // The separate results can then be blended together.
18308   if (VT == MVT::v4i32) {
18309     unsigned Opc = Op.getOpcode();
18310     SDValue Amt0, Amt1, Amt2, Amt3;
18311     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18312       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18313       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18314       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18315       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18316     } else {
18317       // ISD::SHL is handled above but we include it here for completeness.
18318       switch (Opc) {
18319       default:
18320         llvm_unreachable("Unknown target vector shift node");
18321       case ISD::SHL:
18322         Opc = X86ISD::VSHL;
18323         break;
18324       case ISD::SRL:
18325         Opc = X86ISD::VSRL;
18326         break;
18327       case ISD::SRA:
18328         Opc = X86ISD::VSRA;
18329         break;
18330       }
18331       // The SSE2 shifts use the lower i64 as the same shift amount for
18332       // all lanes and the upper i64 is ignored. These shuffle masks
18333       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18334       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18335       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18336       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18337       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18338       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18339     }
18340
18341     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18342     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18343     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18344     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18345     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18346     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18347     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18348   }
18349
18350   if (VT == MVT::v16i8 ||
18351       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18352     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18353     unsigned ShiftOpcode = Op->getOpcode();
18354
18355     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18356       // On SSE41 targets we make use of the fact that VSELECT lowers
18357       // to PBLENDVB which selects bytes based just on the sign bit.
18358       if (Subtarget->hasSSE41()) {
18359         V0 = DAG.getBitcast(VT, V0);
18360         V1 = DAG.getBitcast(VT, V1);
18361         Sel = DAG.getBitcast(VT, Sel);
18362         return DAG.getBitcast(SelVT,
18363                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18364       }
18365       // On pre-SSE41 targets we test for the sign bit by comparing to
18366       // zero - a negative value will set all bits of the lanes to true
18367       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18368       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18369       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18370       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18371     };
18372
18373     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18374     // We can safely do this using i16 shifts as we're only interested in
18375     // the 3 lower bits of each byte.
18376     Amt = DAG.getBitcast(ExtVT, Amt);
18377     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18378     Amt = DAG.getBitcast(VT, Amt);
18379
18380     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18381       // r = VSELECT(r, shift(r, 4), a);
18382       SDValue M =
18383           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18384       R = SignBitSelect(VT, Amt, M, R);
18385
18386       // a += a
18387       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18388
18389       // r = VSELECT(r, shift(r, 2), a);
18390       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18391       R = SignBitSelect(VT, Amt, M, R);
18392
18393       // a += a
18394       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18395
18396       // return VSELECT(r, shift(r, 1), a);
18397       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18398       R = SignBitSelect(VT, Amt, M, R);
18399       return R;
18400     }
18401
18402     if (Op->getOpcode() == ISD::SRA) {
18403       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18404       // so we can correctly sign extend. We don't care what happens to the
18405       // lower byte.
18406       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18407       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18408       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18409       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18410       ALo = DAG.getBitcast(ExtVT, ALo);
18411       AHi = DAG.getBitcast(ExtVT, AHi);
18412       RLo = DAG.getBitcast(ExtVT, RLo);
18413       RHi = DAG.getBitcast(ExtVT, RHi);
18414
18415       // r = VSELECT(r, shift(r, 4), a);
18416       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18417                                 DAG.getConstant(4, dl, ExtVT));
18418       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18419                                 DAG.getConstant(4, dl, ExtVT));
18420       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18421       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18422
18423       // a += a
18424       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18425       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18426
18427       // r = VSELECT(r, shift(r, 2), a);
18428       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18429                         DAG.getConstant(2, dl, ExtVT));
18430       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18431                         DAG.getConstant(2, dl, ExtVT));
18432       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18433       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18434
18435       // a += a
18436       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18437       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18438
18439       // r = VSELECT(r, shift(r, 1), a);
18440       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18441                         DAG.getConstant(1, dl, ExtVT));
18442       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18443                         DAG.getConstant(1, dl, ExtVT));
18444       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18445       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18446
18447       // Logical shift the result back to the lower byte, leaving a zero upper
18448       // byte
18449       // meaning that we can safely pack with PACKUSWB.
18450       RLo =
18451           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18452       RHi =
18453           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18454       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18455     }
18456   }
18457
18458   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18459   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18460   // solution better.
18461   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18462     MVT ExtVT = MVT::v8i32;
18463     unsigned ExtOpc =
18464         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18465     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18466     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18467     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18468                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18469   }
18470
18471   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18472     MVT ExtVT = MVT::v8i32;
18473     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18474     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18475     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18476     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18477     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18478     ALo = DAG.getBitcast(ExtVT, ALo);
18479     AHi = DAG.getBitcast(ExtVT, AHi);
18480     RLo = DAG.getBitcast(ExtVT, RLo);
18481     RHi = DAG.getBitcast(ExtVT, RHi);
18482     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18483     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18484     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18485     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18486     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18487   }
18488
18489   if (VT == MVT::v8i16) {
18490     unsigned ShiftOpcode = Op->getOpcode();
18491
18492     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18493       // On SSE41 targets we make use of the fact that VSELECT lowers
18494       // to PBLENDVB which selects bytes based just on the sign bit.
18495       if (Subtarget->hasSSE41()) {
18496         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18497         V0 = DAG.getBitcast(ExtVT, V0);
18498         V1 = DAG.getBitcast(ExtVT, V1);
18499         Sel = DAG.getBitcast(ExtVT, Sel);
18500         return DAG.getBitcast(
18501             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18502       }
18503       // On pre-SSE41 targets we splat the sign bit - a negative value will
18504       // set all bits of the lanes to true and VSELECT uses that in
18505       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18506       SDValue C =
18507           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18508       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18509     };
18510
18511     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18512     if (Subtarget->hasSSE41()) {
18513       // On SSE41 targets we need to replicate the shift mask in both
18514       // bytes for PBLENDVB.
18515       Amt = DAG.getNode(
18516           ISD::OR, dl, VT,
18517           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18518           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18519     } else {
18520       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18521     }
18522
18523     // r = VSELECT(r, shift(r, 8), a);
18524     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18525     R = SignBitSelect(Amt, M, R);
18526
18527     // a += a
18528     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18529
18530     // r = VSELECT(r, shift(r, 4), a);
18531     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18532     R = SignBitSelect(Amt, M, R);
18533
18534     // a += a
18535     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18536
18537     // r = VSELECT(r, shift(r, 2), a);
18538     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18539     R = SignBitSelect(Amt, M, R);
18540
18541     // a += a
18542     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18543
18544     // return VSELECT(r, shift(r, 1), a);
18545     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18546     R = SignBitSelect(Amt, M, R);
18547     return R;
18548   }
18549
18550   // Decompose 256-bit shifts into smaller 128-bit shifts.
18551   if (VT.is256BitVector()) {
18552     unsigned NumElems = VT.getVectorNumElements();
18553     MVT EltVT = VT.getVectorElementType();
18554     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18555
18556     // Extract the two vectors
18557     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18558     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18559
18560     // Recreate the shift amount vectors
18561     SDValue Amt1, Amt2;
18562     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18563       // Constant shift amount
18564       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18565       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18566       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18567
18568       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18569       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18570     } else {
18571       // Variable shift amount
18572       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18573       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18574     }
18575
18576     // Issue new vector shifts for the smaller types
18577     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18578     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18579
18580     // Concatenate the result back
18581     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18582   }
18583
18584   return SDValue();
18585 }
18586
18587 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18588   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18589   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18590   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18591   // has only one use.
18592   SDNode *N = Op.getNode();
18593   SDValue LHS = N->getOperand(0);
18594   SDValue RHS = N->getOperand(1);
18595   unsigned BaseOp = 0;
18596   unsigned Cond = 0;
18597   SDLoc DL(Op);
18598   switch (Op.getOpcode()) {
18599   default: llvm_unreachable("Unknown ovf instruction!");
18600   case ISD::SADDO:
18601     // A subtract of one will be selected as a INC. Note that INC doesn't
18602     // set CF, so we can't do this for UADDO.
18603     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18604       if (C->isOne()) {
18605         BaseOp = X86ISD::INC;
18606         Cond = X86::COND_O;
18607         break;
18608       }
18609     BaseOp = X86ISD::ADD;
18610     Cond = X86::COND_O;
18611     break;
18612   case ISD::UADDO:
18613     BaseOp = X86ISD::ADD;
18614     Cond = X86::COND_B;
18615     break;
18616   case ISD::SSUBO:
18617     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18618     // set CF, so we can't do this for USUBO.
18619     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18620       if (C->isOne()) {
18621         BaseOp = X86ISD::DEC;
18622         Cond = X86::COND_O;
18623         break;
18624       }
18625     BaseOp = X86ISD::SUB;
18626     Cond = X86::COND_O;
18627     break;
18628   case ISD::USUBO:
18629     BaseOp = X86ISD::SUB;
18630     Cond = X86::COND_B;
18631     break;
18632   case ISD::SMULO:
18633     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18634     Cond = X86::COND_O;
18635     break;
18636   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18637     if (N->getValueType(0) == MVT::i8) {
18638       BaseOp = X86ISD::UMUL8;
18639       Cond = X86::COND_O;
18640       break;
18641     }
18642     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18643                                  MVT::i32);
18644     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18645
18646     SDValue SetCC =
18647       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18648                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18649                   SDValue(Sum.getNode(), 2));
18650
18651     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18652   }
18653   }
18654
18655   // Also sets EFLAGS.
18656   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18657   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18658
18659   SDValue SetCC =
18660     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18661                 DAG.getConstant(Cond, DL, MVT::i32),
18662                 SDValue(Sum.getNode(), 1));
18663
18664   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18665 }
18666
18667 /// Returns true if the operand type is exactly twice the native width, and
18668 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18669 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18670 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18671 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18672   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18673
18674   if (OpWidth == 64)
18675     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18676   else if (OpWidth == 128)
18677     return Subtarget->hasCmpxchg16b();
18678   else
18679     return false;
18680 }
18681
18682 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18683   return needsCmpXchgNb(SI->getValueOperand()->getType());
18684 }
18685
18686 // Note: this turns large loads into lock cmpxchg8b/16b.
18687 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18688 TargetLowering::AtomicExpansionKind
18689 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18690   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18691   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18692                                                : AtomicExpansionKind::None;
18693 }
18694
18695 TargetLowering::AtomicExpansionKind
18696 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18697   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18698   Type *MemType = AI->getType();
18699
18700   // If the operand is too big, we must see if cmpxchg8/16b is available
18701   // and default to library calls otherwise.
18702   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18703     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18704                                    : AtomicExpansionKind::None;
18705   }
18706
18707   AtomicRMWInst::BinOp Op = AI->getOperation();
18708   switch (Op) {
18709   default:
18710     llvm_unreachable("Unknown atomic operation");
18711   case AtomicRMWInst::Xchg:
18712   case AtomicRMWInst::Add:
18713   case AtomicRMWInst::Sub:
18714     // It's better to use xadd, xsub or xchg for these in all cases.
18715     return AtomicExpansionKind::None;
18716   case AtomicRMWInst::Or:
18717   case AtomicRMWInst::And:
18718   case AtomicRMWInst::Xor:
18719     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18720     // prefix to a normal instruction for these operations.
18721     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18722                             : AtomicExpansionKind::None;
18723   case AtomicRMWInst::Nand:
18724   case AtomicRMWInst::Max:
18725   case AtomicRMWInst::Min:
18726   case AtomicRMWInst::UMax:
18727   case AtomicRMWInst::UMin:
18728     // These always require a non-trivial set of data operations on x86. We must
18729     // use a cmpxchg loop.
18730     return AtomicExpansionKind::CmpXChg;
18731   }
18732 }
18733
18734 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18735   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18736   // no-sse2). There isn't any reason to disable it if the target processor
18737   // supports it.
18738   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18739 }
18740
18741 LoadInst *
18742 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18743   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18744   Type *MemType = AI->getType();
18745   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18746   // there is no benefit in turning such RMWs into loads, and it is actually
18747   // harmful as it introduces a mfence.
18748   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18749     return nullptr;
18750
18751   auto Builder = IRBuilder<>(AI);
18752   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18753   auto SynchScope = AI->getSynchScope();
18754   // We must restrict the ordering to avoid generating loads with Release or
18755   // ReleaseAcquire orderings.
18756   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18757   auto Ptr = AI->getPointerOperand();
18758
18759   // Before the load we need a fence. Here is an example lifted from
18760   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18761   // is required:
18762   // Thread 0:
18763   //   x.store(1, relaxed);
18764   //   r1 = y.fetch_add(0, release);
18765   // Thread 1:
18766   //   y.fetch_add(42, acquire);
18767   //   r2 = x.load(relaxed);
18768   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18769   // lowered to just a load without a fence. A mfence flushes the store buffer,
18770   // making the optimization clearly correct.
18771   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18772   // otherwise, we might be able to be more aggressive on relaxed idempotent
18773   // rmw. In practice, they do not look useful, so we don't try to be
18774   // especially clever.
18775   if (SynchScope == SingleThread)
18776     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18777     // the IR level, so we must wrap it in an intrinsic.
18778     return nullptr;
18779
18780   if (!hasMFENCE(*Subtarget))
18781     // FIXME: it might make sense to use a locked operation here but on a
18782     // different cache-line to prevent cache-line bouncing. In practice it
18783     // is probably a small win, and x86 processors without mfence are rare
18784     // enough that we do not bother.
18785     return nullptr;
18786
18787   Function *MFence =
18788       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18789   Builder.CreateCall(MFence, {});
18790
18791   // Finally we can emit the atomic load.
18792   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18793           AI->getType()->getPrimitiveSizeInBits());
18794   Loaded->setAtomic(Order, SynchScope);
18795   AI->replaceAllUsesWith(Loaded);
18796   AI->eraseFromParent();
18797   return Loaded;
18798 }
18799
18800 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18801                                  SelectionDAG &DAG) {
18802   SDLoc dl(Op);
18803   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18804     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18805   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18806     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18807
18808   // The only fence that needs an instruction is a sequentially-consistent
18809   // cross-thread fence.
18810   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18811     if (hasMFENCE(*Subtarget))
18812       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18813
18814     SDValue Chain = Op.getOperand(0);
18815     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18816     SDValue Ops[] = {
18817       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18818       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18819       DAG.getRegister(0, MVT::i32),            // Index
18820       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18821       DAG.getRegister(0, MVT::i32),            // Segment.
18822       Zero,
18823       Chain
18824     };
18825     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18826     return SDValue(Res, 0);
18827   }
18828
18829   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18830   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18831 }
18832
18833 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18834                              SelectionDAG &DAG) {
18835   MVT T = Op.getSimpleValueType();
18836   SDLoc DL(Op);
18837   unsigned Reg = 0;
18838   unsigned size = 0;
18839   switch(T.SimpleTy) {
18840   default: llvm_unreachable("Invalid value type!");
18841   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18842   case MVT::i16: Reg = X86::AX;  size = 2; break;
18843   case MVT::i32: Reg = X86::EAX; size = 4; break;
18844   case MVT::i64:
18845     assert(Subtarget->is64Bit() && "Node not type legal!");
18846     Reg = X86::RAX; size = 8;
18847     break;
18848   }
18849   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18850                                   Op.getOperand(2), SDValue());
18851   SDValue Ops[] = { cpIn.getValue(0),
18852                     Op.getOperand(1),
18853                     Op.getOperand(3),
18854                     DAG.getTargetConstant(size, DL, MVT::i8),
18855                     cpIn.getValue(1) };
18856   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18857   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18858   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18859                                            Ops, T, MMO);
18860
18861   SDValue cpOut =
18862     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18863   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18864                                       MVT::i32, cpOut.getValue(2));
18865   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18866                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18867                                 EFLAGS);
18868
18869   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18870   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18871   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18872   return SDValue();
18873 }
18874
18875 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18876                             SelectionDAG &DAG) {
18877   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18878   MVT DstVT = Op.getSimpleValueType();
18879
18880   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18881     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18882     if (DstVT != MVT::f64)
18883       // This conversion needs to be expanded.
18884       return SDValue();
18885
18886     SDValue InVec = Op->getOperand(0);
18887     SDLoc dl(Op);
18888     unsigned NumElts = SrcVT.getVectorNumElements();
18889     EVT SVT = SrcVT.getVectorElementType();
18890
18891     // Widen the vector in input in the case of MVT::v2i32.
18892     // Example: from MVT::v2i32 to MVT::v4i32.
18893     SmallVector<SDValue, 16> Elts;
18894     for (unsigned i = 0, e = NumElts; i != e; ++i)
18895       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18896                                  DAG.getIntPtrConstant(i, dl)));
18897
18898     // Explicitly mark the extra elements as Undef.
18899     Elts.append(NumElts, DAG.getUNDEF(SVT));
18900
18901     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18902     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18903     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18904     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18905                        DAG.getIntPtrConstant(0, dl));
18906   }
18907
18908   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18909          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18910   assert((DstVT == MVT::i64 ||
18911           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18912          "Unexpected custom BITCAST");
18913   // i64 <=> MMX conversions are Legal.
18914   if (SrcVT==MVT::i64 && DstVT.isVector())
18915     return Op;
18916   if (DstVT==MVT::i64 && SrcVT.isVector())
18917     return Op;
18918   // MMX <=> MMX conversions are Legal.
18919   if (SrcVT.isVector() && DstVT.isVector())
18920     return Op;
18921   // All other conversions need to be expanded.
18922   return SDValue();
18923 }
18924
18925 /// Compute the horizontal sum of bytes in V for the elements of VT.
18926 ///
18927 /// Requires V to be a byte vector and VT to be an integer vector type with
18928 /// wider elements than V's type. The width of the elements of VT determines
18929 /// how many bytes of V are summed horizontally to produce each element of the
18930 /// result.
18931 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18932                                       const X86Subtarget *Subtarget,
18933                                       SelectionDAG &DAG) {
18934   SDLoc DL(V);
18935   MVT ByteVecVT = V.getSimpleValueType();
18936   MVT EltVT = VT.getVectorElementType();
18937   int NumElts = VT.getVectorNumElements();
18938   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18939          "Expected value to have byte element type.");
18940   assert(EltVT != MVT::i8 &&
18941          "Horizontal byte sum only makes sense for wider elements!");
18942   unsigned VecSize = VT.getSizeInBits();
18943   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18944
18945   // PSADBW instruction horizontally add all bytes and leave the result in i64
18946   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18947   if (EltVT == MVT::i64) {
18948     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18949     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18950     return DAG.getBitcast(VT, V);
18951   }
18952
18953   if (EltVT == MVT::i32) {
18954     // We unpack the low half and high half into i32s interleaved with zeros so
18955     // that we can use PSADBW to horizontally sum them. The most useful part of
18956     // this is that it lines up the results of two PSADBW instructions to be
18957     // two v2i64 vectors which concatenated are the 4 population counts. We can
18958     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18959     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18960     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18961     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18962
18963     // Do the horizontal sums into two v2i64s.
18964     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18965     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18966                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18967     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18968                        DAG.getBitcast(ByteVecVT, High), Zeros);
18969
18970     // Merge them together.
18971     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18972     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18973                     DAG.getBitcast(ShortVecVT, Low),
18974                     DAG.getBitcast(ShortVecVT, High));
18975
18976     return DAG.getBitcast(VT, V);
18977   }
18978
18979   // The only element type left is i16.
18980   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18981
18982   // To obtain pop count for each i16 element starting from the pop count for
18983   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18984   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18985   // directly supported.
18986   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18987   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18988   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18989   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18990                   DAG.getBitcast(ByteVecVT, V));
18991   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18992 }
18993
18994 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18995                                         const X86Subtarget *Subtarget,
18996                                         SelectionDAG &DAG) {
18997   MVT VT = Op.getSimpleValueType();
18998   MVT EltVT = VT.getVectorElementType();
18999   unsigned VecSize = VT.getSizeInBits();
19000
19001   // Implement a lookup table in register by using an algorithm based on:
19002   // http://wm.ite.pl/articles/sse-popcount.html
19003   //
19004   // The general idea is that every lower byte nibble in the input vector is an
19005   // index into a in-register pre-computed pop count table. We then split up the
19006   // input vector in two new ones: (1) a vector with only the shifted-right
19007   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19008   // masked out higher ones) for each byte. PSHUB is used separately with both
19009   // to index the in-register table. Next, both are added and the result is a
19010   // i8 vector where each element contains the pop count for input byte.
19011   //
19012   // To obtain the pop count for elements != i8, we follow up with the same
19013   // approach and use additional tricks as described below.
19014   //
19015   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19016                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19017                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19018                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19019
19020   int NumByteElts = VecSize / 8;
19021   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19022   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19023   SmallVector<SDValue, 16> LUTVec;
19024   for (int i = 0; i < NumByteElts; ++i)
19025     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19026   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19027   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19028                                   DAG.getConstant(0x0F, DL, MVT::i8));
19029   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19030
19031   // High nibbles
19032   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19033   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19034   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19035
19036   // Low nibbles
19037   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19038
19039   // The input vector is used as the shuffle mask that index elements into the
19040   // LUT. After counting low and high nibbles, add the vector to obtain the
19041   // final pop count per i8 element.
19042   SDValue HighPopCnt =
19043       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19044   SDValue LowPopCnt =
19045       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19046   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19047
19048   if (EltVT == MVT::i8)
19049     return PopCnt;
19050
19051   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19052 }
19053
19054 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19055                                        const X86Subtarget *Subtarget,
19056                                        SelectionDAG &DAG) {
19057   MVT VT = Op.getSimpleValueType();
19058   assert(VT.is128BitVector() &&
19059          "Only 128-bit vector bitmath lowering supported.");
19060
19061   int VecSize = VT.getSizeInBits();
19062   MVT EltVT = VT.getVectorElementType();
19063   int Len = EltVT.getSizeInBits();
19064
19065   // This is the vectorized version of the "best" algorithm from
19066   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19067   // with a minor tweak to use a series of adds + shifts instead of vector
19068   // multiplications. Implemented for all integer vector types. We only use
19069   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19070   // much faster, even faster than using native popcnt instructions.
19071
19072   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19073     MVT VT = V.getSimpleValueType();
19074     SmallVector<SDValue, 32> Shifters(
19075         VT.getVectorNumElements(),
19076         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19077     return DAG.getNode(OpCode, DL, VT, V,
19078                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19079   };
19080   auto GetMask = [&](SDValue V, APInt Mask) {
19081     MVT VT = V.getSimpleValueType();
19082     SmallVector<SDValue, 32> Masks(
19083         VT.getVectorNumElements(),
19084         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19085     return DAG.getNode(ISD::AND, DL, VT, V,
19086                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19087   };
19088
19089   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19090   // x86, so set the SRL type to have elements at least i16 wide. This is
19091   // correct because all of our SRLs are followed immediately by a mask anyways
19092   // that handles any bits that sneak into the high bits of the byte elements.
19093   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19094
19095   SDValue V = Op;
19096
19097   // v = v - ((v >> 1) & 0x55555555...)
19098   SDValue Srl =
19099       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19100   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19101   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19102
19103   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19104   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19105   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19106   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19107   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19108
19109   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19110   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19111   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19112   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19113
19114   // At this point, V contains the byte-wise population count, and we are
19115   // merely doing a horizontal sum if necessary to get the wider element
19116   // counts.
19117   if (EltVT == MVT::i8)
19118     return V;
19119
19120   return LowerHorizontalByteSum(
19121       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19122       DAG);
19123 }
19124
19125 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19126                                 SelectionDAG &DAG) {
19127   MVT VT = Op.getSimpleValueType();
19128   // FIXME: Need to add AVX-512 support here!
19129   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19130          "Unknown CTPOP type to handle");
19131   SDLoc DL(Op.getNode());
19132   SDValue Op0 = Op.getOperand(0);
19133
19134   if (!Subtarget->hasSSSE3()) {
19135     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19136     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19137     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19138   }
19139
19140   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19141     unsigned NumElems = VT.getVectorNumElements();
19142
19143     // Extract each 128-bit vector, compute pop count and concat the result.
19144     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19145     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19146
19147     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19148                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19149                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19150   }
19151
19152   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19153 }
19154
19155 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19156                           SelectionDAG &DAG) {
19157   assert(Op.getValueType().isVector() &&
19158          "We only do custom lowering for vector population count.");
19159   return LowerVectorCTPOP(Op, Subtarget, DAG);
19160 }
19161
19162 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19163   SDNode *Node = Op.getNode();
19164   SDLoc dl(Node);
19165   EVT T = Node->getValueType(0);
19166   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19167                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19168   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19169                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19170                        Node->getOperand(0),
19171                        Node->getOperand(1), negOp,
19172                        cast<AtomicSDNode>(Node)->getMemOperand(),
19173                        cast<AtomicSDNode>(Node)->getOrdering(),
19174                        cast<AtomicSDNode>(Node)->getSynchScope());
19175 }
19176
19177 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19178   SDNode *Node = Op.getNode();
19179   SDLoc dl(Node);
19180   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19181
19182   // Convert seq_cst store -> xchg
19183   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19184   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19185   //        (The only way to get a 16-byte store is cmpxchg16b)
19186   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19187   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19188       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19189     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19190                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19191                                  Node->getOperand(0),
19192                                  Node->getOperand(1), Node->getOperand(2),
19193                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19194                                  cast<AtomicSDNode>(Node)->getOrdering(),
19195                                  cast<AtomicSDNode>(Node)->getSynchScope());
19196     return Swap.getValue(1);
19197   }
19198   // Other atomic stores have a simple pattern.
19199   return Op;
19200 }
19201
19202 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19203   EVT VT = Op.getNode()->getSimpleValueType(0);
19204
19205   // Let legalize expand this if it isn't a legal type yet.
19206   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19207     return SDValue();
19208
19209   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19210
19211   unsigned Opc;
19212   bool ExtraOp = false;
19213   switch (Op.getOpcode()) {
19214   default: llvm_unreachable("Invalid code");
19215   case ISD::ADDC: Opc = X86ISD::ADD; break;
19216   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19217   case ISD::SUBC: Opc = X86ISD::SUB; break;
19218   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19219   }
19220
19221   if (!ExtraOp)
19222     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19223                        Op.getOperand(1));
19224   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19225                      Op.getOperand(1), Op.getOperand(2));
19226 }
19227
19228 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19229                             SelectionDAG &DAG) {
19230   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19231
19232   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19233   // which returns the values as { float, float } (in XMM0) or
19234   // { double, double } (which is returned in XMM0, XMM1).
19235   SDLoc dl(Op);
19236   SDValue Arg = Op.getOperand(0);
19237   EVT ArgVT = Arg.getValueType();
19238   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19239
19240   TargetLowering::ArgListTy Args;
19241   TargetLowering::ArgListEntry Entry;
19242
19243   Entry.Node = Arg;
19244   Entry.Ty = ArgTy;
19245   Entry.isSExt = false;
19246   Entry.isZExt = false;
19247   Args.push_back(Entry);
19248
19249   bool isF64 = ArgVT == MVT::f64;
19250   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19251   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19252   // the results are returned via SRet in memory.
19253   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19254   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19255   SDValue Callee =
19256       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19257
19258   Type *RetTy = isF64
19259     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19260     : (Type*)VectorType::get(ArgTy, 4);
19261
19262   TargetLowering::CallLoweringInfo CLI(DAG);
19263   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19264     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19265
19266   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19267
19268   if (isF64)
19269     // Returned in xmm0 and xmm1.
19270     return CallResult.first;
19271
19272   // Returned in bits 0:31 and 32:64 xmm0.
19273   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19274                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19275   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19276                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19277   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19278   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19279 }
19280
19281 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19282                              SelectionDAG &DAG) {
19283   assert(Subtarget->hasAVX512() &&
19284          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19285
19286   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19287   EVT VT = N->getValue().getValueType();
19288   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19289   SDLoc dl(Op);
19290
19291   // X86 scatter kills mask register, so its type should be added to
19292   // the list of return values
19293   if (N->getNumValues() == 1) {
19294     SDValue Index = N->getIndex();
19295     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19296         !Index.getValueType().is512BitVector())
19297       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19298
19299     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19300     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19301                       N->getOperand(3), Index };
19302
19303     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19304     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19305     return SDValue(NewScatter.getNode(), 0);
19306   }
19307   return Op;
19308 }
19309
19310 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19311                             SelectionDAG &DAG) {
19312   assert(Subtarget->hasAVX512() &&
19313          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19314
19315   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19316   EVT VT = Op.getValueType();
19317   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19318   SDLoc dl(Op);
19319
19320   SDValue Index = N->getIndex();
19321   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19322       !Index.getValueType().is512BitVector()) {
19323     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19324     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19325                       N->getOperand(3), Index };
19326     DAG.UpdateNodeOperands(N, Ops);
19327   }
19328   return Op;
19329 }
19330
19331 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19332                                                     SelectionDAG &DAG) const {
19333   // TODO: Eventually, the lowering of these nodes should be informed by or
19334   // deferred to the GC strategy for the function in which they appear. For
19335   // now, however, they must be lowered to something. Since they are logically
19336   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19337   // require special handling for these nodes), lower them as literal NOOPs for
19338   // the time being.
19339   SmallVector<SDValue, 2> Ops;
19340
19341   Ops.push_back(Op.getOperand(0));
19342   if (Op->getGluedNode())
19343     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19344
19345   SDLoc OpDL(Op);
19346   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19347   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19348
19349   return NOOP;
19350 }
19351
19352 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19353                                                   SelectionDAG &DAG) const {
19354   // TODO: Eventually, the lowering of these nodes should be informed by or
19355   // deferred to the GC strategy for the function in which they appear. For
19356   // now, however, they must be lowered to something. Since they are logically
19357   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19358   // require special handling for these nodes), lower them as literal NOOPs for
19359   // the time being.
19360   SmallVector<SDValue, 2> Ops;
19361
19362   Ops.push_back(Op.getOperand(0));
19363   if (Op->getGluedNode())
19364     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19365
19366   SDLoc OpDL(Op);
19367   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19368   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19369
19370   return NOOP;
19371 }
19372
19373 /// LowerOperation - Provide custom lowering hooks for some operations.
19374 ///
19375 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19376   switch (Op.getOpcode()) {
19377   default: llvm_unreachable("Should not custom lower this!");
19378   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19379   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19380     return LowerCMP_SWAP(Op, Subtarget, DAG);
19381   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19382   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19383   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19384   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19385   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19386   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19387   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19388   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19389   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19390   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19391   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19392   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19393   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19394   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19395   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19396   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19397   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19398   case ISD::SHL_PARTS:
19399   case ISD::SRA_PARTS:
19400   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19401   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19402   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19403   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19404   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19405   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19406   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19407   case ISD::SIGN_EXTEND_VECTOR_INREG:
19408     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19409   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19410   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19411   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19412   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19413   case ISD::FABS:
19414   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19415   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19416   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19417   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19418   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19419   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19420   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19421   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19422   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19423   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19424   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19425   case ISD::INTRINSIC_VOID:
19426   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19427   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19428   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19429   case ISD::FRAME_TO_ARGS_OFFSET:
19430                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19431   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19432   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19433   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19434   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19435   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19436   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19437   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19438   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19439   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19440   case ISD::CTTZ:
19441   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19442   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19443   case ISD::UMUL_LOHI:
19444   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19445   case ISD::SRA:
19446   case ISD::SRL:
19447   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19448   case ISD::SADDO:
19449   case ISD::UADDO:
19450   case ISD::SSUBO:
19451   case ISD::USUBO:
19452   case ISD::SMULO:
19453   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19454   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19455   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19456   case ISD::ADDC:
19457   case ISD::ADDE:
19458   case ISD::SUBC:
19459   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19460   case ISD::ADD:                return LowerADD(Op, DAG);
19461   case ISD::SUB:                return LowerSUB(Op, DAG);
19462   case ISD::SMAX:
19463   case ISD::SMIN:
19464   case ISD::UMAX:
19465   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19466   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19467   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19468   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19469   case ISD::GC_TRANSITION_START:
19470                                 return LowerGC_TRANSITION_START(Op, DAG);
19471   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19472   }
19473 }
19474
19475 /// ReplaceNodeResults - Replace a node with an illegal result type
19476 /// with a new node built out of custom code.
19477 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19478                                            SmallVectorImpl<SDValue>&Results,
19479                                            SelectionDAG &DAG) const {
19480   SDLoc dl(N);
19481   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19482   switch (N->getOpcode()) {
19483   default:
19484     llvm_unreachable("Do not know how to custom type legalize this operation!");
19485   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19486   case X86ISD::FMINC:
19487   case X86ISD::FMIN:
19488   case X86ISD::FMAXC:
19489   case X86ISD::FMAX: {
19490     EVT VT = N->getValueType(0);
19491     if (VT != MVT::v2f32)
19492       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19493     SDValue UNDEF = DAG.getUNDEF(VT);
19494     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19495                               N->getOperand(0), UNDEF);
19496     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19497                               N->getOperand(1), UNDEF);
19498     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19499     return;
19500   }
19501   case ISD::SIGN_EXTEND_INREG:
19502   case ISD::ADDC:
19503   case ISD::ADDE:
19504   case ISD::SUBC:
19505   case ISD::SUBE:
19506     // We don't want to expand or promote these.
19507     return;
19508   case ISD::SDIV:
19509   case ISD::UDIV:
19510   case ISD::SREM:
19511   case ISD::UREM:
19512   case ISD::SDIVREM:
19513   case ISD::UDIVREM: {
19514     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19515     Results.push_back(V);
19516     return;
19517   }
19518   case ISD::FP_TO_SINT:
19519   case ISD::FP_TO_UINT: {
19520     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19521
19522     std::pair<SDValue,SDValue> Vals =
19523         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19524     SDValue FIST = Vals.first, StackSlot = Vals.second;
19525     if (FIST.getNode()) {
19526       EVT VT = N->getValueType(0);
19527       // Return a load from the stack slot.
19528       if (StackSlot.getNode())
19529         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19530                                       MachinePointerInfo(),
19531                                       false, false, false, 0));
19532       else
19533         Results.push_back(FIST);
19534     }
19535     return;
19536   }
19537   case ISD::UINT_TO_FP: {
19538     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19539     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19540         N->getValueType(0) != MVT::v2f32)
19541       return;
19542     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19543                                  N->getOperand(0));
19544     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19545                                      MVT::f64);
19546     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19547     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19548                              DAG.getBitcast(MVT::v2i64, VBias));
19549     Or = DAG.getBitcast(MVT::v2f64, Or);
19550     // TODO: Are there any fast-math-flags to propagate here?
19551     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19552     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19553     return;
19554   }
19555   case ISD::FP_ROUND: {
19556     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19557         return;
19558     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19559     Results.push_back(V);
19560     return;
19561   }
19562   case ISD::FP_EXTEND: {
19563     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19564     // No other ValueType for FP_EXTEND should reach this point.
19565     assert(N->getValueType(0) == MVT::v2f32 &&
19566            "Do not know how to legalize this Node");
19567     return;
19568   }
19569   case ISD::INTRINSIC_W_CHAIN: {
19570     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19571     switch (IntNo) {
19572     default : llvm_unreachable("Do not know how to custom type "
19573                                "legalize this intrinsic operation!");
19574     case Intrinsic::x86_rdtsc:
19575       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19576                                      Results);
19577     case Intrinsic::x86_rdtscp:
19578       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19579                                      Results);
19580     case Intrinsic::x86_rdpmc:
19581       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19582     }
19583   }
19584   case ISD::READCYCLECOUNTER: {
19585     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19586                                    Results);
19587   }
19588   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19589     EVT T = N->getValueType(0);
19590     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19591     bool Regs64bit = T == MVT::i128;
19592     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19593     SDValue cpInL, cpInH;
19594     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19595                         DAG.getConstant(0, dl, HalfT));
19596     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19597                         DAG.getConstant(1, dl, HalfT));
19598     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19599                              Regs64bit ? X86::RAX : X86::EAX,
19600                              cpInL, SDValue());
19601     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19602                              Regs64bit ? X86::RDX : X86::EDX,
19603                              cpInH, cpInL.getValue(1));
19604     SDValue swapInL, swapInH;
19605     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19606                           DAG.getConstant(0, dl, HalfT));
19607     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19608                           DAG.getConstant(1, dl, HalfT));
19609     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19610                                Regs64bit ? X86::RBX : X86::EBX,
19611                                swapInL, cpInH.getValue(1));
19612     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19613                                Regs64bit ? X86::RCX : X86::ECX,
19614                                swapInH, swapInL.getValue(1));
19615     SDValue Ops[] = { swapInH.getValue(0),
19616                       N->getOperand(1),
19617                       swapInH.getValue(1) };
19618     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19619     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19620     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19621                                   X86ISD::LCMPXCHG8_DAG;
19622     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19623     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19624                                         Regs64bit ? X86::RAX : X86::EAX,
19625                                         HalfT, Result.getValue(1));
19626     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19627                                         Regs64bit ? X86::RDX : X86::EDX,
19628                                         HalfT, cpOutL.getValue(2));
19629     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19630
19631     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19632                                         MVT::i32, cpOutH.getValue(2));
19633     SDValue Success =
19634         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19635                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19636     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19637
19638     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19639     Results.push_back(Success);
19640     Results.push_back(EFLAGS.getValue(1));
19641     return;
19642   }
19643   case ISD::ATOMIC_SWAP:
19644   case ISD::ATOMIC_LOAD_ADD:
19645   case ISD::ATOMIC_LOAD_SUB:
19646   case ISD::ATOMIC_LOAD_AND:
19647   case ISD::ATOMIC_LOAD_OR:
19648   case ISD::ATOMIC_LOAD_XOR:
19649   case ISD::ATOMIC_LOAD_NAND:
19650   case ISD::ATOMIC_LOAD_MIN:
19651   case ISD::ATOMIC_LOAD_MAX:
19652   case ISD::ATOMIC_LOAD_UMIN:
19653   case ISD::ATOMIC_LOAD_UMAX:
19654   case ISD::ATOMIC_LOAD: {
19655     // Delegate to generic TypeLegalization. Situations we can really handle
19656     // should have already been dealt with by AtomicExpandPass.cpp.
19657     break;
19658   }
19659   case ISD::BITCAST: {
19660     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19661     EVT DstVT = N->getValueType(0);
19662     EVT SrcVT = N->getOperand(0)->getValueType(0);
19663
19664     if (SrcVT != MVT::f64 ||
19665         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19666       return;
19667
19668     unsigned NumElts = DstVT.getVectorNumElements();
19669     EVT SVT = DstVT.getVectorElementType();
19670     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19671     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19672                                    MVT::v2f64, N->getOperand(0));
19673     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19674
19675     if (ExperimentalVectorWideningLegalization) {
19676       // If we are legalizing vectors by widening, we already have the desired
19677       // legal vector type, just return it.
19678       Results.push_back(ToVecInt);
19679       return;
19680     }
19681
19682     SmallVector<SDValue, 8> Elts;
19683     for (unsigned i = 0, e = NumElts; i != e; ++i)
19684       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19685                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19686
19687     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19688   }
19689   }
19690 }
19691
19692 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19693   switch ((X86ISD::NodeType)Opcode) {
19694   case X86ISD::FIRST_NUMBER:       break;
19695   case X86ISD::BSF:                return "X86ISD::BSF";
19696   case X86ISD::BSR:                return "X86ISD::BSR";
19697   case X86ISD::SHLD:               return "X86ISD::SHLD";
19698   case X86ISD::SHRD:               return "X86ISD::SHRD";
19699   case X86ISD::FAND:               return "X86ISD::FAND";
19700   case X86ISD::FANDN:              return "X86ISD::FANDN";
19701   case X86ISD::FOR:                return "X86ISD::FOR";
19702   case X86ISD::FXOR:               return "X86ISD::FXOR";
19703   case X86ISD::FILD:               return "X86ISD::FILD";
19704   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19705   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19706   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19707   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19708   case X86ISD::FLD:                return "X86ISD::FLD";
19709   case X86ISD::FST:                return "X86ISD::FST";
19710   case X86ISD::CALL:               return "X86ISD::CALL";
19711   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19712   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19713   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19714   case X86ISD::BT:                 return "X86ISD::BT";
19715   case X86ISD::CMP:                return "X86ISD::CMP";
19716   case X86ISD::COMI:               return "X86ISD::COMI";
19717   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19718   case X86ISD::CMPM:               return "X86ISD::CMPM";
19719   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19720   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19721   case X86ISD::SETCC:              return "X86ISD::SETCC";
19722   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19723   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19724   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19725   case X86ISD::CMOV:               return "X86ISD::CMOV";
19726   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19727   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19728   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19729   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19730   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19731   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19732   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19733   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19734   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19735   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19736   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19737   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19738   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19739   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19740   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19741   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19742   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19743   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19744   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19745   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19746   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19747   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19748   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19749   case X86ISD::HADD:               return "X86ISD::HADD";
19750   case X86ISD::HSUB:               return "X86ISD::HSUB";
19751   case X86ISD::FHADD:              return "X86ISD::FHADD";
19752   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19753   case X86ISD::ABS:                return "X86ISD::ABS";
19754   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19755   case X86ISD::FMAX:               return "X86ISD::FMAX";
19756   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19757   case X86ISD::FMIN:               return "X86ISD::FMIN";
19758   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19759   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19760   case X86ISD::FMINC:              return "X86ISD::FMINC";
19761   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19762   case X86ISD::FRCP:               return "X86ISD::FRCP";
19763   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19764   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19765   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19766   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19767   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19768   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19769   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19770   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19771   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19772   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19773   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19774   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19775   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19776   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19777   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19778   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19779   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19780   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19781   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19782   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19783   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19784   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19785   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19786   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19787   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19788   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19789   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19790   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19791   case X86ISD::VSHL:               return "X86ISD::VSHL";
19792   case X86ISD::VSRL:               return "X86ISD::VSRL";
19793   case X86ISD::VSRA:               return "X86ISD::VSRA";
19794   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19795   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19796   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19797   case X86ISD::CMPP:               return "X86ISD::CMPP";
19798   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19799   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19800   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19801   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19802   case X86ISD::ADD:                return "X86ISD::ADD";
19803   case X86ISD::SUB:                return "X86ISD::SUB";
19804   case X86ISD::ADC:                return "X86ISD::ADC";
19805   case X86ISD::SBB:                return "X86ISD::SBB";
19806   case X86ISD::SMUL:               return "X86ISD::SMUL";
19807   case X86ISD::UMUL:               return "X86ISD::UMUL";
19808   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19809   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19810   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19811   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19812   case X86ISD::INC:                return "X86ISD::INC";
19813   case X86ISD::DEC:                return "X86ISD::DEC";
19814   case X86ISD::OR:                 return "X86ISD::OR";
19815   case X86ISD::XOR:                return "X86ISD::XOR";
19816   case X86ISD::AND:                return "X86ISD::AND";
19817   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19818   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19819   case X86ISD::PTEST:              return "X86ISD::PTEST";
19820   case X86ISD::TESTP:              return "X86ISD::TESTP";
19821   case X86ISD::TESTM:              return "X86ISD::TESTM";
19822   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19823   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19824   case X86ISD::KTEST:              return "X86ISD::KTEST";
19825   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19826   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19827   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19828   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19829   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19830   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19831   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19832   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19833   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19834   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19835   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19836   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19837   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19838   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19839   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19840   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19841   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19842   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19843   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19844   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19845   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19846   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19847   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19848   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19849   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19850   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19851   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19852   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19853   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19854   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19855   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19856   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19857   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19858   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19859   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19860   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19861   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19862   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19863   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19864   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19865   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19866   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19867   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19868   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19869   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19870   case X86ISD::SAHF:               return "X86ISD::SAHF";
19871   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19872   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19873   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19874   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19875   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
19876   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
19877   case X86ISD::FMADD:              return "X86ISD::FMADD";
19878   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19879   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19880   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19881   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19882   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19883   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19884   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19885   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19886   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19887   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19888   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19889   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19890   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19891   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19892   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19893   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19894   case X86ISD::XTEST:              return "X86ISD::XTEST";
19895   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19896   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19897   case X86ISD::SELECT:             return "X86ISD::SELECT";
19898   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19899   case X86ISD::RCP28:              return "X86ISD::RCP28";
19900   case X86ISD::EXP2:               return "X86ISD::EXP2";
19901   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19902   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19903   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19904   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19905   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19906   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19907   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19908   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19909   case X86ISD::ADDS:               return "X86ISD::ADDS";
19910   case X86ISD::SUBS:               return "X86ISD::SUBS";
19911   case X86ISD::AVG:                return "X86ISD::AVG";
19912   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19913   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19914   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19915   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19916   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19917   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
19918   }
19919   return nullptr;
19920 }
19921
19922 // isLegalAddressingMode - Return true if the addressing mode represented
19923 // by AM is legal for this target, for a load/store of the specified type.
19924 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19925                                               const AddrMode &AM, Type *Ty,
19926                                               unsigned AS) const {
19927   // X86 supports extremely general addressing modes.
19928   CodeModel::Model M = getTargetMachine().getCodeModel();
19929   Reloc::Model R = getTargetMachine().getRelocationModel();
19930
19931   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19932   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19933     return false;
19934
19935   if (AM.BaseGV) {
19936     unsigned GVFlags =
19937       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19938
19939     // If a reference to this global requires an extra load, we can't fold it.
19940     if (isGlobalStubReference(GVFlags))
19941       return false;
19942
19943     // If BaseGV requires a register for the PIC base, we cannot also have a
19944     // BaseReg specified.
19945     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19946       return false;
19947
19948     // If lower 4G is not available, then we must use rip-relative addressing.
19949     if ((M != CodeModel::Small || R != Reloc::Static) &&
19950         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19951       return false;
19952   }
19953
19954   switch (AM.Scale) {
19955   case 0:
19956   case 1:
19957   case 2:
19958   case 4:
19959   case 8:
19960     // These scales always work.
19961     break;
19962   case 3:
19963   case 5:
19964   case 9:
19965     // These scales are formed with basereg+scalereg.  Only accept if there is
19966     // no basereg yet.
19967     if (AM.HasBaseReg)
19968       return false;
19969     break;
19970   default:  // Other stuff never works.
19971     return false;
19972   }
19973
19974   return true;
19975 }
19976
19977 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19978   unsigned Bits = Ty->getScalarSizeInBits();
19979
19980   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19981   // particularly cheaper than those without.
19982   if (Bits == 8)
19983     return false;
19984
19985   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19986   // variable shifts just as cheap as scalar ones.
19987   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19988     return false;
19989
19990   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19991   // fully general vector.
19992   return true;
19993 }
19994
19995 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19996   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19997     return false;
19998   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19999   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20000   return NumBits1 > NumBits2;
20001 }
20002
20003 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20004   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20005     return false;
20006
20007   if (!isTypeLegal(EVT::getEVT(Ty1)))
20008     return false;
20009
20010   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20011
20012   // Assuming the caller doesn't have a zeroext or signext return parameter,
20013   // truncation all the way down to i1 is valid.
20014   return true;
20015 }
20016
20017 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20018   return isInt<32>(Imm);
20019 }
20020
20021 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20022   // Can also use sub to handle negated immediates.
20023   return isInt<32>(Imm);
20024 }
20025
20026 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20027   if (!VT1.isInteger() || !VT2.isInteger())
20028     return false;
20029   unsigned NumBits1 = VT1.getSizeInBits();
20030   unsigned NumBits2 = VT2.getSizeInBits();
20031   return NumBits1 > NumBits2;
20032 }
20033
20034 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20035   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20036   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20037 }
20038
20039 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20040   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20041   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20042 }
20043
20044 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20045   EVT VT1 = Val.getValueType();
20046   if (isZExtFree(VT1, VT2))
20047     return true;
20048
20049   if (Val.getOpcode() != ISD::LOAD)
20050     return false;
20051
20052   if (!VT1.isSimple() || !VT1.isInteger() ||
20053       !VT2.isSimple() || !VT2.isInteger())
20054     return false;
20055
20056   switch (VT1.getSimpleVT().SimpleTy) {
20057   default: break;
20058   case MVT::i8:
20059   case MVT::i16:
20060   case MVT::i32:
20061     // X86 has 8, 16, and 32-bit zero-extending loads.
20062     return true;
20063   }
20064
20065   return false;
20066 }
20067
20068 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20069
20070 bool
20071 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20072   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20073     return false;
20074
20075   VT = VT.getScalarType();
20076
20077   if (!VT.isSimple())
20078     return false;
20079
20080   switch (VT.getSimpleVT().SimpleTy) {
20081   case MVT::f32:
20082   case MVT::f64:
20083     return true;
20084   default:
20085     break;
20086   }
20087
20088   return false;
20089 }
20090
20091 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20092   // i16 instructions are longer (0x66 prefix) and potentially slower.
20093   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20094 }
20095
20096 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20097 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20098 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20099 /// are assumed to be legal.
20100 bool
20101 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20102                                       EVT VT) const {
20103   if (!VT.isSimple())
20104     return false;
20105
20106   // Not for i1 vectors
20107   if (VT.getScalarType() == MVT::i1)
20108     return false;
20109
20110   // Very little shuffling can be done for 64-bit vectors right now.
20111   if (VT.getSizeInBits() == 64)
20112     return false;
20113
20114   // We only care that the types being shuffled are legal. The lowering can
20115   // handle any possible shuffle mask that results.
20116   return isTypeLegal(VT.getSimpleVT());
20117 }
20118
20119 bool
20120 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20121                                           EVT VT) const {
20122   // Just delegate to the generic legality, clear masks aren't special.
20123   return isShuffleMaskLegal(Mask, VT);
20124 }
20125
20126 //===----------------------------------------------------------------------===//
20127 //                           X86 Scheduler Hooks
20128 //===----------------------------------------------------------------------===//
20129
20130 /// Utility function to emit xbegin specifying the start of an RTM region.
20131 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20132                                      const TargetInstrInfo *TII) {
20133   DebugLoc DL = MI->getDebugLoc();
20134
20135   const BasicBlock *BB = MBB->getBasicBlock();
20136   MachineFunction::iterator I = MBB;
20137   ++I;
20138
20139   // For the v = xbegin(), we generate
20140   //
20141   // thisMBB:
20142   //  xbegin sinkMBB
20143   //
20144   // mainMBB:
20145   //  eax = -1
20146   //
20147   // sinkMBB:
20148   //  v = eax
20149
20150   MachineBasicBlock *thisMBB = MBB;
20151   MachineFunction *MF = MBB->getParent();
20152   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20153   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20154   MF->insert(I, mainMBB);
20155   MF->insert(I, sinkMBB);
20156
20157   // Transfer the remainder of BB and its successor edges to sinkMBB.
20158   sinkMBB->splice(sinkMBB->begin(), MBB,
20159                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20160   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20161
20162   // thisMBB:
20163   //  xbegin sinkMBB
20164   //  # fallthrough to mainMBB
20165   //  # abortion to sinkMBB
20166   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20167   thisMBB->addSuccessor(mainMBB);
20168   thisMBB->addSuccessor(sinkMBB);
20169
20170   // mainMBB:
20171   //  EAX = -1
20172   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20173   mainMBB->addSuccessor(sinkMBB);
20174
20175   // sinkMBB:
20176   // EAX is live into the sinkMBB
20177   sinkMBB->addLiveIn(X86::EAX);
20178   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20179           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20180     .addReg(X86::EAX);
20181
20182   MI->eraseFromParent();
20183   return sinkMBB;
20184 }
20185
20186 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20187 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20188 // in the .td file.
20189 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20190                                        const TargetInstrInfo *TII) {
20191   unsigned Opc;
20192   switch (MI->getOpcode()) {
20193   default: llvm_unreachable("illegal opcode!");
20194   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20195   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20196   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20197   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20198   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20199   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20200   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20201   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20202   }
20203
20204   DebugLoc dl = MI->getDebugLoc();
20205   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20206
20207   unsigned NumArgs = MI->getNumOperands();
20208   for (unsigned i = 1; i < NumArgs; ++i) {
20209     MachineOperand &Op = MI->getOperand(i);
20210     if (!(Op.isReg() && Op.isImplicit()))
20211       MIB.addOperand(Op);
20212   }
20213   if (MI->hasOneMemOperand())
20214     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20215
20216   BuildMI(*BB, MI, dl,
20217     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20218     .addReg(X86::XMM0);
20219
20220   MI->eraseFromParent();
20221   return BB;
20222 }
20223
20224 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20225 // defs in an instruction pattern
20226 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20227                                        const TargetInstrInfo *TII) {
20228   unsigned Opc;
20229   switch (MI->getOpcode()) {
20230   default: llvm_unreachable("illegal opcode!");
20231   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20232   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20233   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20234   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20235   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20236   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20237   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20238   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20239   }
20240
20241   DebugLoc dl = MI->getDebugLoc();
20242   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20243
20244   unsigned NumArgs = MI->getNumOperands(); // remove the results
20245   for (unsigned i = 1; i < NumArgs; ++i) {
20246     MachineOperand &Op = MI->getOperand(i);
20247     if (!(Op.isReg() && Op.isImplicit()))
20248       MIB.addOperand(Op);
20249   }
20250   if (MI->hasOneMemOperand())
20251     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20252
20253   BuildMI(*BB, MI, dl,
20254     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20255     .addReg(X86::ECX);
20256
20257   MI->eraseFromParent();
20258   return BB;
20259 }
20260
20261 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20262                                       const X86Subtarget *Subtarget) {
20263   DebugLoc dl = MI->getDebugLoc();
20264   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20265   // Address into RAX/EAX, other two args into ECX, EDX.
20266   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20267   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20268   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20269   for (int i = 0; i < X86::AddrNumOperands; ++i)
20270     MIB.addOperand(MI->getOperand(i));
20271
20272   unsigned ValOps = X86::AddrNumOperands;
20273   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20274     .addReg(MI->getOperand(ValOps).getReg());
20275   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20276     .addReg(MI->getOperand(ValOps+1).getReg());
20277
20278   // The instruction doesn't actually take any operands though.
20279   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20280
20281   MI->eraseFromParent(); // The pseudo is gone now.
20282   return BB;
20283 }
20284
20285 MachineBasicBlock *
20286 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20287                                                  MachineBasicBlock *MBB) const {
20288   // Emit va_arg instruction on X86-64.
20289
20290   // Operands to this pseudo-instruction:
20291   // 0  ) Output        : destination address (reg)
20292   // 1-5) Input         : va_list address (addr, i64mem)
20293   // 6  ) ArgSize       : Size (in bytes) of vararg type
20294   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20295   // 8  ) Align         : Alignment of type
20296   // 9  ) EFLAGS (implicit-def)
20297
20298   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20299   static_assert(X86::AddrNumOperands == 5,
20300                 "VAARG_64 assumes 5 address operands");
20301
20302   unsigned DestReg = MI->getOperand(0).getReg();
20303   MachineOperand &Base = MI->getOperand(1);
20304   MachineOperand &Scale = MI->getOperand(2);
20305   MachineOperand &Index = MI->getOperand(3);
20306   MachineOperand &Disp = MI->getOperand(4);
20307   MachineOperand &Segment = MI->getOperand(5);
20308   unsigned ArgSize = MI->getOperand(6).getImm();
20309   unsigned ArgMode = MI->getOperand(7).getImm();
20310   unsigned Align = MI->getOperand(8).getImm();
20311
20312   // Memory Reference
20313   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20314   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20315   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20316
20317   // Machine Information
20318   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20319   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20320   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20321   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20322   DebugLoc DL = MI->getDebugLoc();
20323
20324   // struct va_list {
20325   //   i32   gp_offset
20326   //   i32   fp_offset
20327   //   i64   overflow_area (address)
20328   //   i64   reg_save_area (address)
20329   // }
20330   // sizeof(va_list) = 24
20331   // alignment(va_list) = 8
20332
20333   unsigned TotalNumIntRegs = 6;
20334   unsigned TotalNumXMMRegs = 8;
20335   bool UseGPOffset = (ArgMode == 1);
20336   bool UseFPOffset = (ArgMode == 2);
20337   unsigned MaxOffset = TotalNumIntRegs * 8 +
20338                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20339
20340   /* Align ArgSize to a multiple of 8 */
20341   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20342   bool NeedsAlign = (Align > 8);
20343
20344   MachineBasicBlock *thisMBB = MBB;
20345   MachineBasicBlock *overflowMBB;
20346   MachineBasicBlock *offsetMBB;
20347   MachineBasicBlock *endMBB;
20348
20349   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20350   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20351   unsigned OffsetReg = 0;
20352
20353   if (!UseGPOffset && !UseFPOffset) {
20354     // If we only pull from the overflow region, we don't create a branch.
20355     // We don't need to alter control flow.
20356     OffsetDestReg = 0; // unused
20357     OverflowDestReg = DestReg;
20358
20359     offsetMBB = nullptr;
20360     overflowMBB = thisMBB;
20361     endMBB = thisMBB;
20362   } else {
20363     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20364     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20365     // If not, pull from overflow_area. (branch to overflowMBB)
20366     //
20367     //       thisMBB
20368     //         |     .
20369     //         |        .
20370     //     offsetMBB   overflowMBB
20371     //         |        .
20372     //         |     .
20373     //        endMBB
20374
20375     // Registers for the PHI in endMBB
20376     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20377     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20378
20379     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20380     MachineFunction *MF = MBB->getParent();
20381     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20382     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20383     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20384
20385     MachineFunction::iterator MBBIter = MBB;
20386     ++MBBIter;
20387
20388     // Insert the new basic blocks
20389     MF->insert(MBBIter, offsetMBB);
20390     MF->insert(MBBIter, overflowMBB);
20391     MF->insert(MBBIter, endMBB);
20392
20393     // Transfer the remainder of MBB and its successor edges to endMBB.
20394     endMBB->splice(endMBB->begin(), thisMBB,
20395                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20396     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20397
20398     // Make offsetMBB and overflowMBB successors of thisMBB
20399     thisMBB->addSuccessor(offsetMBB);
20400     thisMBB->addSuccessor(overflowMBB);
20401
20402     // endMBB is a successor of both offsetMBB and overflowMBB
20403     offsetMBB->addSuccessor(endMBB);
20404     overflowMBB->addSuccessor(endMBB);
20405
20406     // Load the offset value into a register
20407     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20408     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20409       .addOperand(Base)
20410       .addOperand(Scale)
20411       .addOperand(Index)
20412       .addDisp(Disp, UseFPOffset ? 4 : 0)
20413       .addOperand(Segment)
20414       .setMemRefs(MMOBegin, MMOEnd);
20415
20416     // Check if there is enough room left to pull this argument.
20417     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20418       .addReg(OffsetReg)
20419       .addImm(MaxOffset + 8 - ArgSizeA8);
20420
20421     // Branch to "overflowMBB" if offset >= max
20422     // Fall through to "offsetMBB" otherwise
20423     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20424       .addMBB(overflowMBB);
20425   }
20426
20427   // In offsetMBB, emit code to use the reg_save_area.
20428   if (offsetMBB) {
20429     assert(OffsetReg != 0);
20430
20431     // Read the reg_save_area address.
20432     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20433     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20434       .addOperand(Base)
20435       .addOperand(Scale)
20436       .addOperand(Index)
20437       .addDisp(Disp, 16)
20438       .addOperand(Segment)
20439       .setMemRefs(MMOBegin, MMOEnd);
20440
20441     // Zero-extend the offset
20442     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20443       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20444         .addImm(0)
20445         .addReg(OffsetReg)
20446         .addImm(X86::sub_32bit);
20447
20448     // Add the offset to the reg_save_area to get the final address.
20449     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20450       .addReg(OffsetReg64)
20451       .addReg(RegSaveReg);
20452
20453     // Compute the offset for the next argument
20454     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20455     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20456       .addReg(OffsetReg)
20457       .addImm(UseFPOffset ? 16 : 8);
20458
20459     // Store it back into the va_list.
20460     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20461       .addOperand(Base)
20462       .addOperand(Scale)
20463       .addOperand(Index)
20464       .addDisp(Disp, UseFPOffset ? 4 : 0)
20465       .addOperand(Segment)
20466       .addReg(NextOffsetReg)
20467       .setMemRefs(MMOBegin, MMOEnd);
20468
20469     // Jump to endMBB
20470     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20471       .addMBB(endMBB);
20472   }
20473
20474   //
20475   // Emit code to use overflow area
20476   //
20477
20478   // Load the overflow_area address into a register.
20479   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20480   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20481     .addOperand(Base)
20482     .addOperand(Scale)
20483     .addOperand(Index)
20484     .addDisp(Disp, 8)
20485     .addOperand(Segment)
20486     .setMemRefs(MMOBegin, MMOEnd);
20487
20488   // If we need to align it, do so. Otherwise, just copy the address
20489   // to OverflowDestReg.
20490   if (NeedsAlign) {
20491     // Align the overflow address
20492     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20493     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20494
20495     // aligned_addr = (addr + (align-1)) & ~(align-1)
20496     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20497       .addReg(OverflowAddrReg)
20498       .addImm(Align-1);
20499
20500     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20501       .addReg(TmpReg)
20502       .addImm(~(uint64_t)(Align-1));
20503   } else {
20504     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20505       .addReg(OverflowAddrReg);
20506   }
20507
20508   // Compute the next overflow address after this argument.
20509   // (the overflow address should be kept 8-byte aligned)
20510   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20511   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20512     .addReg(OverflowDestReg)
20513     .addImm(ArgSizeA8);
20514
20515   // Store the new overflow address.
20516   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20517     .addOperand(Base)
20518     .addOperand(Scale)
20519     .addOperand(Index)
20520     .addDisp(Disp, 8)
20521     .addOperand(Segment)
20522     .addReg(NextAddrReg)
20523     .setMemRefs(MMOBegin, MMOEnd);
20524
20525   // If we branched, emit the PHI to the front of endMBB.
20526   if (offsetMBB) {
20527     BuildMI(*endMBB, endMBB->begin(), DL,
20528             TII->get(X86::PHI), DestReg)
20529       .addReg(OffsetDestReg).addMBB(offsetMBB)
20530       .addReg(OverflowDestReg).addMBB(overflowMBB);
20531   }
20532
20533   // Erase the pseudo instruction
20534   MI->eraseFromParent();
20535
20536   return endMBB;
20537 }
20538
20539 MachineBasicBlock *
20540 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20541                                                  MachineInstr *MI,
20542                                                  MachineBasicBlock *MBB) const {
20543   // Emit code to save XMM registers to the stack. The ABI says that the
20544   // number of registers to save is given in %al, so it's theoretically
20545   // possible to do an indirect jump trick to avoid saving all of them,
20546   // however this code takes a simpler approach and just executes all
20547   // of the stores if %al is non-zero. It's less code, and it's probably
20548   // easier on the hardware branch predictor, and stores aren't all that
20549   // expensive anyway.
20550
20551   // Create the new basic blocks. One block contains all the XMM stores,
20552   // and one block is the final destination regardless of whether any
20553   // stores were performed.
20554   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20555   MachineFunction *F = MBB->getParent();
20556   MachineFunction::iterator MBBIter = MBB;
20557   ++MBBIter;
20558   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20559   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20560   F->insert(MBBIter, XMMSaveMBB);
20561   F->insert(MBBIter, EndMBB);
20562
20563   // Transfer the remainder of MBB and its successor edges to EndMBB.
20564   EndMBB->splice(EndMBB->begin(), MBB,
20565                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20566   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20567
20568   // The original block will now fall through to the XMM save block.
20569   MBB->addSuccessor(XMMSaveMBB);
20570   // The XMMSaveMBB will fall through to the end block.
20571   XMMSaveMBB->addSuccessor(EndMBB);
20572
20573   // Now add the instructions.
20574   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20575   DebugLoc DL = MI->getDebugLoc();
20576
20577   unsigned CountReg = MI->getOperand(0).getReg();
20578   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20579   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20580
20581   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20582     // If %al is 0, branch around the XMM save block.
20583     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20584     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20585     MBB->addSuccessor(EndMBB);
20586   }
20587
20588   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20589   // that was just emitted, but clearly shouldn't be "saved".
20590   assert((MI->getNumOperands() <= 3 ||
20591           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20592           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20593          && "Expected last argument to be EFLAGS");
20594   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20595   // In the XMM save block, save all the XMM argument registers.
20596   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20597     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20598     MachineMemOperand *MMO = F->getMachineMemOperand(
20599         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20600         MachineMemOperand::MOStore,
20601         /*Size=*/16, /*Align=*/16);
20602     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20603       .addFrameIndex(RegSaveFrameIndex)
20604       .addImm(/*Scale=*/1)
20605       .addReg(/*IndexReg=*/0)
20606       .addImm(/*Disp=*/Offset)
20607       .addReg(/*Segment=*/0)
20608       .addReg(MI->getOperand(i).getReg())
20609       .addMemOperand(MMO);
20610   }
20611
20612   MI->eraseFromParent();   // The pseudo instruction is gone now.
20613
20614   return EndMBB;
20615 }
20616
20617 // The EFLAGS operand of SelectItr might be missing a kill marker
20618 // because there were multiple uses of EFLAGS, and ISel didn't know
20619 // which to mark. Figure out whether SelectItr should have had a
20620 // kill marker, and set it if it should. Returns the correct kill
20621 // marker value.
20622 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20623                                      MachineBasicBlock* BB,
20624                                      const TargetRegisterInfo* TRI) {
20625   // Scan forward through BB for a use/def of EFLAGS.
20626   MachineBasicBlock::iterator miI(std::next(SelectItr));
20627   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20628     const MachineInstr& mi = *miI;
20629     if (mi.readsRegister(X86::EFLAGS))
20630       return false;
20631     if (mi.definesRegister(X86::EFLAGS))
20632       break; // Should have kill-flag - update below.
20633   }
20634
20635   // If we hit the end of the block, check whether EFLAGS is live into a
20636   // successor.
20637   if (miI == BB->end()) {
20638     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20639                                           sEnd = BB->succ_end();
20640          sItr != sEnd; ++sItr) {
20641       MachineBasicBlock* succ = *sItr;
20642       if (succ->isLiveIn(X86::EFLAGS))
20643         return false;
20644     }
20645   }
20646
20647   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20648   // out. SelectMI should have a kill flag on EFLAGS.
20649   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20650   return true;
20651 }
20652
20653 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20654 // together with other CMOV pseudo-opcodes into a single basic-block with
20655 // conditional jump around it.
20656 static bool isCMOVPseudo(MachineInstr *MI) {
20657   switch (MI->getOpcode()) {
20658   case X86::CMOV_FR32:
20659   case X86::CMOV_FR64:
20660   case X86::CMOV_GR8:
20661   case X86::CMOV_GR16:
20662   case X86::CMOV_GR32:
20663   case X86::CMOV_RFP32:
20664   case X86::CMOV_RFP64:
20665   case X86::CMOV_RFP80:
20666   case X86::CMOV_V2F64:
20667   case X86::CMOV_V2I64:
20668   case X86::CMOV_V4F32:
20669   case X86::CMOV_V4F64:
20670   case X86::CMOV_V4I64:
20671   case X86::CMOV_V16F32:
20672   case X86::CMOV_V8F32:
20673   case X86::CMOV_V8F64:
20674   case X86::CMOV_V8I64:
20675   case X86::CMOV_V8I1:
20676   case X86::CMOV_V16I1:
20677   case X86::CMOV_V32I1:
20678   case X86::CMOV_V64I1:
20679     return true;
20680
20681   default:
20682     return false;
20683   }
20684 }
20685
20686 MachineBasicBlock *
20687 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20688                                      MachineBasicBlock *BB) const {
20689   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20690   DebugLoc DL = MI->getDebugLoc();
20691
20692   // To "insert" a SELECT_CC instruction, we actually have to insert the
20693   // diamond control-flow pattern.  The incoming instruction knows the
20694   // destination vreg to set, the condition code register to branch on, the
20695   // true/false values to select between, and a branch opcode to use.
20696   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20697   MachineFunction::iterator It = BB;
20698   ++It;
20699
20700   //  thisMBB:
20701   //  ...
20702   //   TrueVal = ...
20703   //   cmpTY ccX, r1, r2
20704   //   bCC copy1MBB
20705   //   fallthrough --> copy0MBB
20706   MachineBasicBlock *thisMBB = BB;
20707   MachineFunction *F = BB->getParent();
20708
20709   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20710   // as described above, by inserting a BB, and then making a PHI at the join
20711   // point to select the true and false operands of the CMOV in the PHI.
20712   //
20713   // The code also handles two different cases of multiple CMOV opcodes
20714   // in a row.
20715   //
20716   // Case 1:
20717   // In this case, there are multiple CMOVs in a row, all which are based on
20718   // the same condition setting (or the exact opposite condition setting).
20719   // In this case we can lower all the CMOVs using a single inserted BB, and
20720   // then make a number of PHIs at the join point to model the CMOVs. The only
20721   // trickiness here, is that in a case like:
20722   //
20723   // t2 = CMOV cond1 t1, f1
20724   // t3 = CMOV cond1 t2, f2
20725   //
20726   // when rewriting this into PHIs, we have to perform some renaming on the
20727   // temps since you cannot have a PHI operand refer to a PHI result earlier
20728   // in the same block.  The "simple" but wrong lowering would be:
20729   //
20730   // t2 = PHI t1(BB1), f1(BB2)
20731   // t3 = PHI t2(BB1), f2(BB2)
20732   //
20733   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20734   // renaming is to note that on the path through BB1, t2 is really just a
20735   // copy of t1, and do that renaming, properly generating:
20736   //
20737   // t2 = PHI t1(BB1), f1(BB2)
20738   // t3 = PHI t1(BB1), f2(BB2)
20739   //
20740   // Case 2, we lower cascaded CMOVs such as
20741   //
20742   //   (CMOV (CMOV F, T, cc1), T, cc2)
20743   //
20744   // to two successives branches.  For that, we look for another CMOV as the
20745   // following instruction.
20746   //
20747   // Without this, we would add a PHI between the two jumps, which ends up
20748   // creating a few copies all around. For instance, for
20749   //
20750   //    (sitofp (zext (fcmp une)))
20751   //
20752   // we would generate:
20753   //
20754   //         ucomiss %xmm1, %xmm0
20755   //         movss  <1.0f>, %xmm0
20756   //         movaps  %xmm0, %xmm1
20757   //         jne     .LBB5_2
20758   //         xorps   %xmm1, %xmm1
20759   // .LBB5_2:
20760   //         jp      .LBB5_4
20761   //         movaps  %xmm1, %xmm0
20762   // .LBB5_4:
20763   //         retq
20764   //
20765   // because this custom-inserter would have generated:
20766   //
20767   //   A
20768   //   | \
20769   //   |  B
20770   //   | /
20771   //   C
20772   //   | \
20773   //   |  D
20774   //   | /
20775   //   E
20776   //
20777   // A: X = ...; Y = ...
20778   // B: empty
20779   // C: Z = PHI [X, A], [Y, B]
20780   // D: empty
20781   // E: PHI [X, C], [Z, D]
20782   //
20783   // If we lower both CMOVs in a single step, we can instead generate:
20784   //
20785   //   A
20786   //   | \
20787   //   |  C
20788   //   | /|
20789   //   |/ |
20790   //   |  |
20791   //   |  D
20792   //   | /
20793   //   E
20794   //
20795   // A: X = ...; Y = ...
20796   // D: empty
20797   // E: PHI [X, A], [X, C], [Y, D]
20798   //
20799   // Which, in our sitofp/fcmp example, gives us something like:
20800   //
20801   //         ucomiss %xmm1, %xmm0
20802   //         movss  <1.0f>, %xmm0
20803   //         jne     .LBB5_4
20804   //         jp      .LBB5_4
20805   //         xorps   %xmm0, %xmm0
20806   // .LBB5_4:
20807   //         retq
20808   //
20809   MachineInstr *CascadedCMOV = nullptr;
20810   MachineInstr *LastCMOV = MI;
20811   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20812   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20813   MachineBasicBlock::iterator NextMIIt =
20814       std::next(MachineBasicBlock::iterator(MI));
20815
20816   // Check for case 1, where there are multiple CMOVs with the same condition
20817   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20818   // number of jumps the most.
20819
20820   if (isCMOVPseudo(MI)) {
20821     // See if we have a string of CMOVS with the same condition.
20822     while (NextMIIt != BB->end() &&
20823            isCMOVPseudo(NextMIIt) &&
20824            (NextMIIt->getOperand(3).getImm() == CC ||
20825             NextMIIt->getOperand(3).getImm() == OppCC)) {
20826       LastCMOV = &*NextMIIt;
20827       ++NextMIIt;
20828     }
20829   }
20830
20831   // This checks for case 2, but only do this if we didn't already find
20832   // case 1, as indicated by LastCMOV == MI.
20833   if (LastCMOV == MI &&
20834       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20835       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20836       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20837     CascadedCMOV = &*NextMIIt;
20838   }
20839
20840   MachineBasicBlock *jcc1MBB = nullptr;
20841
20842   // If we have a cascaded CMOV, we lower it to two successive branches to
20843   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20844   if (CascadedCMOV) {
20845     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20846     F->insert(It, jcc1MBB);
20847     jcc1MBB->addLiveIn(X86::EFLAGS);
20848   }
20849
20850   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20851   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20852   F->insert(It, copy0MBB);
20853   F->insert(It, sinkMBB);
20854
20855   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20856   // live into the sink and copy blocks.
20857   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20858
20859   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20860   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20861       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20862     copy0MBB->addLiveIn(X86::EFLAGS);
20863     sinkMBB->addLiveIn(X86::EFLAGS);
20864   }
20865
20866   // Transfer the remainder of BB and its successor edges to sinkMBB.
20867   sinkMBB->splice(sinkMBB->begin(), BB,
20868                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20869   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20870
20871   // Add the true and fallthrough blocks as its successors.
20872   if (CascadedCMOV) {
20873     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20874     BB->addSuccessor(jcc1MBB);
20875
20876     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20877     // jump to the sinkMBB.
20878     jcc1MBB->addSuccessor(copy0MBB);
20879     jcc1MBB->addSuccessor(sinkMBB);
20880   } else {
20881     BB->addSuccessor(copy0MBB);
20882   }
20883
20884   // The true block target of the first (or only) branch is always sinkMBB.
20885   BB->addSuccessor(sinkMBB);
20886
20887   // Create the conditional branch instruction.
20888   unsigned Opc = X86::GetCondBranchFromCond(CC);
20889   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20890
20891   if (CascadedCMOV) {
20892     unsigned Opc2 = X86::GetCondBranchFromCond(
20893         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20894     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20895   }
20896
20897   //  copy0MBB:
20898   //   %FalseValue = ...
20899   //   # fallthrough to sinkMBB
20900   copy0MBB->addSuccessor(sinkMBB);
20901
20902   //  sinkMBB:
20903   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20904   //  ...
20905   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20906   MachineBasicBlock::iterator MIItEnd =
20907     std::next(MachineBasicBlock::iterator(LastCMOV));
20908   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20909   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20910   MachineInstrBuilder MIB;
20911
20912   // As we are creating the PHIs, we have to be careful if there is more than
20913   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20914   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20915   // That also means that PHI construction must work forward from earlier to
20916   // later, and that the code must maintain a mapping from earlier PHI's
20917   // destination registers, and the registers that went into the PHI.
20918
20919   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20920     unsigned DestReg = MIIt->getOperand(0).getReg();
20921     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20922     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20923
20924     // If this CMOV we are generating is the opposite condition from
20925     // the jump we generated, then we have to swap the operands for the
20926     // PHI that is going to be generated.
20927     if (MIIt->getOperand(3).getImm() == OppCC)
20928         std::swap(Op1Reg, Op2Reg);
20929
20930     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20931       Op1Reg = RegRewriteTable[Op1Reg].first;
20932
20933     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20934       Op2Reg = RegRewriteTable[Op2Reg].second;
20935
20936     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20937                   TII->get(X86::PHI), DestReg)
20938           .addReg(Op1Reg).addMBB(copy0MBB)
20939           .addReg(Op2Reg).addMBB(thisMBB);
20940
20941     // Add this PHI to the rewrite table.
20942     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20943   }
20944
20945   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20946   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20947   if (CascadedCMOV) {
20948     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20949     // Copy the PHI result to the register defined by the second CMOV.
20950     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20951             DL, TII->get(TargetOpcode::COPY),
20952             CascadedCMOV->getOperand(0).getReg())
20953         .addReg(MI->getOperand(0).getReg());
20954     CascadedCMOV->eraseFromParent();
20955   }
20956
20957   // Now remove the CMOV(s).
20958   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20959     (MIIt++)->eraseFromParent();
20960
20961   return sinkMBB;
20962 }
20963
20964 MachineBasicBlock *
20965 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20966                                        MachineBasicBlock *BB) const {
20967   // Combine the following atomic floating-point modification pattern:
20968   //   a.store(reg OP a.load(acquire), release)
20969   // Transform them into:
20970   //   OPss (%gpr), %xmm
20971   //   movss %xmm, (%gpr)
20972   // Or sd equivalent for 64-bit operations.
20973   unsigned MOp, FOp;
20974   switch (MI->getOpcode()) {
20975   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20976   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20977   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20978   }
20979   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20980   DebugLoc DL = MI->getDebugLoc();
20981   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20982   unsigned MSrc = MI->getOperand(0).getReg();
20983   unsigned VSrc = MI->getOperand(5).getReg();
20984   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20985                                 .addReg(/*Base=*/MSrc)
20986                                 .addImm(/*Scale=*/1)
20987                                 .addReg(/*Index=*/0)
20988                                 .addImm(0)
20989                                 .addReg(0);
20990   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20991                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20992                           .addReg(VSrc)
20993                           .addReg(/*Base=*/MSrc)
20994                           .addImm(/*Scale=*/1)
20995                           .addReg(/*Index=*/0)
20996                           .addImm(/*Disp=*/0)
20997                           .addReg(/*Segment=*/0);
20998   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20999   MI->eraseFromParent(); // The pseudo instruction is gone now.
21000   return BB;
21001 }
21002
21003 MachineBasicBlock *
21004 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21005                                         MachineBasicBlock *BB) const {
21006   MachineFunction *MF = BB->getParent();
21007   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21008   DebugLoc DL = MI->getDebugLoc();
21009   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21010
21011   assert(MF->shouldSplitStack());
21012
21013   const bool Is64Bit = Subtarget->is64Bit();
21014   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21015
21016   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21017   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21018
21019   // BB:
21020   //  ... [Till the alloca]
21021   // If stacklet is not large enough, jump to mallocMBB
21022   //
21023   // bumpMBB:
21024   //  Allocate by subtracting from RSP
21025   //  Jump to continueMBB
21026   //
21027   // mallocMBB:
21028   //  Allocate by call to runtime
21029   //
21030   // continueMBB:
21031   //  ...
21032   //  [rest of original BB]
21033   //
21034
21035   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21036   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21037   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21038
21039   MachineRegisterInfo &MRI = MF->getRegInfo();
21040   const TargetRegisterClass *AddrRegClass =
21041       getRegClassFor(getPointerTy(MF->getDataLayout()));
21042
21043   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21044     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21045     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21046     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21047     sizeVReg = MI->getOperand(1).getReg(),
21048     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21049
21050   MachineFunction::iterator MBBIter = BB;
21051   ++MBBIter;
21052
21053   MF->insert(MBBIter, bumpMBB);
21054   MF->insert(MBBIter, mallocMBB);
21055   MF->insert(MBBIter, continueMBB);
21056
21057   continueMBB->splice(continueMBB->begin(), BB,
21058                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21059   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21060
21061   // Add code to the main basic block to check if the stack limit has been hit,
21062   // and if so, jump to mallocMBB otherwise to bumpMBB.
21063   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21064   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21065     .addReg(tmpSPVReg).addReg(sizeVReg);
21066   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21067     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21068     .addReg(SPLimitVReg);
21069   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21070
21071   // bumpMBB simply decreases the stack pointer, since we know the current
21072   // stacklet has enough space.
21073   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21074     .addReg(SPLimitVReg);
21075   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21076     .addReg(SPLimitVReg);
21077   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21078
21079   // Calls into a routine in libgcc to allocate more space from the heap.
21080   const uint32_t *RegMask =
21081       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21082   if (IsLP64) {
21083     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21084       .addReg(sizeVReg);
21085     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21086       .addExternalSymbol("__morestack_allocate_stack_space")
21087       .addRegMask(RegMask)
21088       .addReg(X86::RDI, RegState::Implicit)
21089       .addReg(X86::RAX, RegState::ImplicitDefine);
21090   } else if (Is64Bit) {
21091     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21092       .addReg(sizeVReg);
21093     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21094       .addExternalSymbol("__morestack_allocate_stack_space")
21095       .addRegMask(RegMask)
21096       .addReg(X86::EDI, RegState::Implicit)
21097       .addReg(X86::EAX, RegState::ImplicitDefine);
21098   } else {
21099     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21100       .addImm(12);
21101     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21102     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21103       .addExternalSymbol("__morestack_allocate_stack_space")
21104       .addRegMask(RegMask)
21105       .addReg(X86::EAX, RegState::ImplicitDefine);
21106   }
21107
21108   if (!Is64Bit)
21109     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21110       .addImm(16);
21111
21112   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21113     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21114   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21115
21116   // Set up the CFG correctly.
21117   BB->addSuccessor(bumpMBB);
21118   BB->addSuccessor(mallocMBB);
21119   mallocMBB->addSuccessor(continueMBB);
21120   bumpMBB->addSuccessor(continueMBB);
21121
21122   // Take care of the PHI nodes.
21123   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21124           MI->getOperand(0).getReg())
21125     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21126     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21127
21128   // Delete the original pseudo instruction.
21129   MI->eraseFromParent();
21130
21131   // And we're done.
21132   return continueMBB;
21133 }
21134
21135 MachineBasicBlock *
21136 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21137                                         MachineBasicBlock *BB) const {
21138   DebugLoc DL = MI->getDebugLoc();
21139
21140   assert(!Subtarget->isTargetMachO());
21141
21142   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21143                                                     DL);
21144
21145   MI->eraseFromParent();   // The pseudo instruction is gone now.
21146   return BB;
21147 }
21148
21149 MachineBasicBlock *
21150 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21151                                       MachineBasicBlock *BB) const {
21152   // This is pretty easy.  We're taking the value that we received from
21153   // our load from the relocation, sticking it in either RDI (x86-64)
21154   // or EAX and doing an indirect call.  The return value will then
21155   // be in the normal return register.
21156   MachineFunction *F = BB->getParent();
21157   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21158   DebugLoc DL = MI->getDebugLoc();
21159
21160   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21161   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21162
21163   // Get a register mask for the lowered call.
21164   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21165   // proper register mask.
21166   const uint32_t *RegMask =
21167       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21168   if (Subtarget->is64Bit()) {
21169     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21170                                       TII->get(X86::MOV64rm), X86::RDI)
21171     .addReg(X86::RIP)
21172     .addImm(0).addReg(0)
21173     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21174                       MI->getOperand(3).getTargetFlags())
21175     .addReg(0);
21176     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21177     addDirectMem(MIB, X86::RDI);
21178     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21179   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21180     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21181                                       TII->get(X86::MOV32rm), X86::EAX)
21182     .addReg(0)
21183     .addImm(0).addReg(0)
21184     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21185                       MI->getOperand(3).getTargetFlags())
21186     .addReg(0);
21187     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21188     addDirectMem(MIB, X86::EAX);
21189     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21190   } else {
21191     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21192                                       TII->get(X86::MOV32rm), X86::EAX)
21193     .addReg(TII->getGlobalBaseReg(F))
21194     .addImm(0).addReg(0)
21195     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21196                       MI->getOperand(3).getTargetFlags())
21197     .addReg(0);
21198     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21199     addDirectMem(MIB, X86::EAX);
21200     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21201   }
21202
21203   MI->eraseFromParent(); // The pseudo instruction is gone now.
21204   return BB;
21205 }
21206
21207 MachineBasicBlock *
21208 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21209                                     MachineBasicBlock *MBB) const {
21210   DebugLoc DL = MI->getDebugLoc();
21211   MachineFunction *MF = MBB->getParent();
21212   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21213   MachineRegisterInfo &MRI = MF->getRegInfo();
21214
21215   const BasicBlock *BB = MBB->getBasicBlock();
21216   MachineFunction::iterator I = MBB;
21217   ++I;
21218
21219   // Memory Reference
21220   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21221   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21222
21223   unsigned DstReg;
21224   unsigned MemOpndSlot = 0;
21225
21226   unsigned CurOp = 0;
21227
21228   DstReg = MI->getOperand(CurOp++).getReg();
21229   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21230   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21231   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21232   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21233
21234   MemOpndSlot = CurOp;
21235
21236   MVT PVT = getPointerTy(MF->getDataLayout());
21237   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21238          "Invalid Pointer Size!");
21239
21240   // For v = setjmp(buf), we generate
21241   //
21242   // thisMBB:
21243   //  buf[LabelOffset] = restoreMBB
21244   //  SjLjSetup restoreMBB
21245   //
21246   // mainMBB:
21247   //  v_main = 0
21248   //
21249   // sinkMBB:
21250   //  v = phi(main, restore)
21251   //
21252   // restoreMBB:
21253   //  if base pointer being used, load it from frame
21254   //  v_restore = 1
21255
21256   MachineBasicBlock *thisMBB = MBB;
21257   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21258   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21259   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21260   MF->insert(I, mainMBB);
21261   MF->insert(I, sinkMBB);
21262   MF->push_back(restoreMBB);
21263
21264   MachineInstrBuilder MIB;
21265
21266   // Transfer the remainder of BB and its successor edges to sinkMBB.
21267   sinkMBB->splice(sinkMBB->begin(), MBB,
21268                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21269   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21270
21271   // thisMBB:
21272   unsigned PtrStoreOpc = 0;
21273   unsigned LabelReg = 0;
21274   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21275   Reloc::Model RM = MF->getTarget().getRelocationModel();
21276   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21277                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21278
21279   // Prepare IP either in reg or imm.
21280   if (!UseImmLabel) {
21281     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21282     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21283     LabelReg = MRI.createVirtualRegister(PtrRC);
21284     if (Subtarget->is64Bit()) {
21285       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21286               .addReg(X86::RIP)
21287               .addImm(0)
21288               .addReg(0)
21289               .addMBB(restoreMBB)
21290               .addReg(0);
21291     } else {
21292       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21293       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21294               .addReg(XII->getGlobalBaseReg(MF))
21295               .addImm(0)
21296               .addReg(0)
21297               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21298               .addReg(0);
21299     }
21300   } else
21301     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21302   // Store IP
21303   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21304   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21305     if (i == X86::AddrDisp)
21306       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21307     else
21308       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21309   }
21310   if (!UseImmLabel)
21311     MIB.addReg(LabelReg);
21312   else
21313     MIB.addMBB(restoreMBB);
21314   MIB.setMemRefs(MMOBegin, MMOEnd);
21315   // Setup
21316   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21317           .addMBB(restoreMBB);
21318
21319   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21320   MIB.addRegMask(RegInfo->getNoPreservedMask());
21321   thisMBB->addSuccessor(mainMBB);
21322   thisMBB->addSuccessor(restoreMBB);
21323
21324   // mainMBB:
21325   //  EAX = 0
21326   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21327   mainMBB->addSuccessor(sinkMBB);
21328
21329   // sinkMBB:
21330   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21331           TII->get(X86::PHI), DstReg)
21332     .addReg(mainDstReg).addMBB(mainMBB)
21333     .addReg(restoreDstReg).addMBB(restoreMBB);
21334
21335   // restoreMBB:
21336   if (RegInfo->hasBasePointer(*MF)) {
21337     const bool Uses64BitFramePtr =
21338         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21339     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21340     X86FI->setRestoreBasePointer(MF);
21341     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21342     unsigned BasePtr = RegInfo->getBaseRegister();
21343     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21344     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21345                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21346       .setMIFlag(MachineInstr::FrameSetup);
21347   }
21348   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21349   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21350   restoreMBB->addSuccessor(sinkMBB);
21351
21352   MI->eraseFromParent();
21353   return sinkMBB;
21354 }
21355
21356 MachineBasicBlock *
21357 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21358                                      MachineBasicBlock *MBB) const {
21359   DebugLoc DL = MI->getDebugLoc();
21360   MachineFunction *MF = MBB->getParent();
21361   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21362   MachineRegisterInfo &MRI = MF->getRegInfo();
21363
21364   // Memory Reference
21365   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21366   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21367
21368   MVT PVT = getPointerTy(MF->getDataLayout());
21369   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21370          "Invalid Pointer Size!");
21371
21372   const TargetRegisterClass *RC =
21373     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21374   unsigned Tmp = MRI.createVirtualRegister(RC);
21375   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21376   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21377   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21378   unsigned SP = RegInfo->getStackRegister();
21379
21380   MachineInstrBuilder MIB;
21381
21382   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21383   const int64_t SPOffset = 2 * PVT.getStoreSize();
21384
21385   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21386   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21387
21388   // Reload FP
21389   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21390   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21391     MIB.addOperand(MI->getOperand(i));
21392   MIB.setMemRefs(MMOBegin, MMOEnd);
21393   // Reload IP
21394   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21395   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21396     if (i == X86::AddrDisp)
21397       MIB.addDisp(MI->getOperand(i), LabelOffset);
21398     else
21399       MIB.addOperand(MI->getOperand(i));
21400   }
21401   MIB.setMemRefs(MMOBegin, MMOEnd);
21402   // Reload SP
21403   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21404   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21405     if (i == X86::AddrDisp)
21406       MIB.addDisp(MI->getOperand(i), SPOffset);
21407     else
21408       MIB.addOperand(MI->getOperand(i));
21409   }
21410   MIB.setMemRefs(MMOBegin, MMOEnd);
21411   // Jump
21412   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21413
21414   MI->eraseFromParent();
21415   return MBB;
21416 }
21417
21418 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21419 // accumulator loops. Writing back to the accumulator allows the coalescer
21420 // to remove extra copies in the loop.
21421 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21422 MachineBasicBlock *
21423 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21424                                  MachineBasicBlock *MBB) const {
21425   MachineOperand &AddendOp = MI->getOperand(3);
21426
21427   // Bail out early if the addend isn't a register - we can't switch these.
21428   if (!AddendOp.isReg())
21429     return MBB;
21430
21431   MachineFunction &MF = *MBB->getParent();
21432   MachineRegisterInfo &MRI = MF.getRegInfo();
21433
21434   // Check whether the addend is defined by a PHI:
21435   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21436   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21437   if (!AddendDef.isPHI())
21438     return MBB;
21439
21440   // Look for the following pattern:
21441   // loop:
21442   //   %addend = phi [%entry, 0], [%loop, %result]
21443   //   ...
21444   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21445
21446   // Replace with:
21447   //   loop:
21448   //   %addend = phi [%entry, 0], [%loop, %result]
21449   //   ...
21450   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21451
21452   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21453     assert(AddendDef.getOperand(i).isReg());
21454     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21455     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21456     if (&PHISrcInst == MI) {
21457       // Found a matching instruction.
21458       unsigned NewFMAOpc = 0;
21459       switch (MI->getOpcode()) {
21460         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21461         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21462         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21463         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21464         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21465         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21466         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21467         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21468         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21469         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21470         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21471         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21472         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21473         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21474         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21475         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21476         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21477         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21478         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21479         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21480
21481         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21482         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21483         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21484         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21485         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21486         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21487         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21488         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21489         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21490         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21491         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21492         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21493         default: llvm_unreachable("Unrecognized FMA variant.");
21494       }
21495
21496       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21497       MachineInstrBuilder MIB =
21498         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21499         .addOperand(MI->getOperand(0))
21500         .addOperand(MI->getOperand(3))
21501         .addOperand(MI->getOperand(2))
21502         .addOperand(MI->getOperand(1));
21503       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21504       MI->eraseFromParent();
21505     }
21506   }
21507
21508   return MBB;
21509 }
21510
21511 MachineBasicBlock *
21512 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21513                                                MachineBasicBlock *BB) const {
21514   switch (MI->getOpcode()) {
21515   default: llvm_unreachable("Unexpected instr type to insert");
21516   case X86::TAILJMPd64:
21517   case X86::TAILJMPr64:
21518   case X86::TAILJMPm64:
21519   case X86::TAILJMPd64_REX:
21520   case X86::TAILJMPr64_REX:
21521   case X86::TAILJMPm64_REX:
21522     llvm_unreachable("TAILJMP64 would not be touched here.");
21523   case X86::TCRETURNdi64:
21524   case X86::TCRETURNri64:
21525   case X86::TCRETURNmi64:
21526     return BB;
21527   case X86::WIN_ALLOCA:
21528     return EmitLoweredWinAlloca(MI, BB);
21529   case X86::SEG_ALLOCA_32:
21530   case X86::SEG_ALLOCA_64:
21531     return EmitLoweredSegAlloca(MI, BB);
21532   case X86::TLSCall_32:
21533   case X86::TLSCall_64:
21534     return EmitLoweredTLSCall(MI, BB);
21535   case X86::CMOV_FR32:
21536   case X86::CMOV_FR64:
21537   case X86::CMOV_GR8:
21538   case X86::CMOV_GR16:
21539   case X86::CMOV_GR32:
21540   case X86::CMOV_RFP32:
21541   case X86::CMOV_RFP64:
21542   case X86::CMOV_RFP80:
21543   case X86::CMOV_V2F64:
21544   case X86::CMOV_V2I64:
21545   case X86::CMOV_V4F32:
21546   case X86::CMOV_V4F64:
21547   case X86::CMOV_V4I64:
21548   case X86::CMOV_V16F32:
21549   case X86::CMOV_V8F32:
21550   case X86::CMOV_V8F64:
21551   case X86::CMOV_V8I64:
21552   case X86::CMOV_V8I1:
21553   case X86::CMOV_V16I1:
21554   case X86::CMOV_V32I1:
21555   case X86::CMOV_V64I1:
21556     return EmitLoweredSelect(MI, BB);
21557
21558   case X86::RELEASE_FADD32mr:
21559   case X86::RELEASE_FADD64mr:
21560     return EmitLoweredAtomicFP(MI, BB);
21561
21562   case X86::FP32_TO_INT16_IN_MEM:
21563   case X86::FP32_TO_INT32_IN_MEM:
21564   case X86::FP32_TO_INT64_IN_MEM:
21565   case X86::FP64_TO_INT16_IN_MEM:
21566   case X86::FP64_TO_INT32_IN_MEM:
21567   case X86::FP64_TO_INT64_IN_MEM:
21568   case X86::FP80_TO_INT16_IN_MEM:
21569   case X86::FP80_TO_INT32_IN_MEM:
21570   case X86::FP80_TO_INT64_IN_MEM: {
21571     MachineFunction *F = BB->getParent();
21572     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21573     DebugLoc DL = MI->getDebugLoc();
21574
21575     // Change the floating point control register to use "round towards zero"
21576     // mode when truncating to an integer value.
21577     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21578     addFrameReference(BuildMI(*BB, MI, DL,
21579                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21580
21581     // Load the old value of the high byte of the control word...
21582     unsigned OldCW =
21583       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21584     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21585                       CWFrameIdx);
21586
21587     // Set the high part to be round to zero...
21588     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21589       .addImm(0xC7F);
21590
21591     // Reload the modified control word now...
21592     addFrameReference(BuildMI(*BB, MI, DL,
21593                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21594
21595     // Restore the memory image of control word to original value
21596     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21597       .addReg(OldCW);
21598
21599     // Get the X86 opcode to use.
21600     unsigned Opc;
21601     switch (MI->getOpcode()) {
21602     default: llvm_unreachable("illegal opcode!");
21603     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21604     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21605     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21606     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21607     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21608     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21609     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21610     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21611     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21612     }
21613
21614     X86AddressMode AM;
21615     MachineOperand &Op = MI->getOperand(0);
21616     if (Op.isReg()) {
21617       AM.BaseType = X86AddressMode::RegBase;
21618       AM.Base.Reg = Op.getReg();
21619     } else {
21620       AM.BaseType = X86AddressMode::FrameIndexBase;
21621       AM.Base.FrameIndex = Op.getIndex();
21622     }
21623     Op = MI->getOperand(1);
21624     if (Op.isImm())
21625       AM.Scale = Op.getImm();
21626     Op = MI->getOperand(2);
21627     if (Op.isImm())
21628       AM.IndexReg = Op.getImm();
21629     Op = MI->getOperand(3);
21630     if (Op.isGlobal()) {
21631       AM.GV = Op.getGlobal();
21632     } else {
21633       AM.Disp = Op.getImm();
21634     }
21635     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21636                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21637
21638     // Reload the original control word now.
21639     addFrameReference(BuildMI(*BB, MI, DL,
21640                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21641
21642     MI->eraseFromParent();   // The pseudo instruction is gone now.
21643     return BB;
21644   }
21645     // String/text processing lowering.
21646   case X86::PCMPISTRM128REG:
21647   case X86::VPCMPISTRM128REG:
21648   case X86::PCMPISTRM128MEM:
21649   case X86::VPCMPISTRM128MEM:
21650   case X86::PCMPESTRM128REG:
21651   case X86::VPCMPESTRM128REG:
21652   case X86::PCMPESTRM128MEM:
21653   case X86::VPCMPESTRM128MEM:
21654     assert(Subtarget->hasSSE42() &&
21655            "Target must have SSE4.2 or AVX features enabled");
21656     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21657
21658   // String/text processing lowering.
21659   case X86::PCMPISTRIREG:
21660   case X86::VPCMPISTRIREG:
21661   case X86::PCMPISTRIMEM:
21662   case X86::VPCMPISTRIMEM:
21663   case X86::PCMPESTRIREG:
21664   case X86::VPCMPESTRIREG:
21665   case X86::PCMPESTRIMEM:
21666   case X86::VPCMPESTRIMEM:
21667     assert(Subtarget->hasSSE42() &&
21668            "Target must have SSE4.2 or AVX features enabled");
21669     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21670
21671   // Thread synchronization.
21672   case X86::MONITOR:
21673     return EmitMonitor(MI, BB, Subtarget);
21674
21675   // xbegin
21676   case X86::XBEGIN:
21677     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21678
21679   case X86::VASTART_SAVE_XMM_REGS:
21680     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21681
21682   case X86::VAARG_64:
21683     return EmitVAARG64WithCustomInserter(MI, BB);
21684
21685   case X86::EH_SjLj_SetJmp32:
21686   case X86::EH_SjLj_SetJmp64:
21687     return emitEHSjLjSetJmp(MI, BB);
21688
21689   case X86::EH_SjLj_LongJmp32:
21690   case X86::EH_SjLj_LongJmp64:
21691     return emitEHSjLjLongJmp(MI, BB);
21692
21693   case TargetOpcode::STATEPOINT:
21694     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21695     // this point in the process.  We diverge later.
21696     return emitPatchPoint(MI, BB);
21697
21698   case TargetOpcode::STACKMAP:
21699   case TargetOpcode::PATCHPOINT:
21700     return emitPatchPoint(MI, BB);
21701
21702   case X86::VFMADDPDr213r:
21703   case X86::VFMADDPSr213r:
21704   case X86::VFMADDSDr213r:
21705   case X86::VFMADDSSr213r:
21706   case X86::VFMSUBPDr213r:
21707   case X86::VFMSUBPSr213r:
21708   case X86::VFMSUBSDr213r:
21709   case X86::VFMSUBSSr213r:
21710   case X86::VFNMADDPDr213r:
21711   case X86::VFNMADDPSr213r:
21712   case X86::VFNMADDSDr213r:
21713   case X86::VFNMADDSSr213r:
21714   case X86::VFNMSUBPDr213r:
21715   case X86::VFNMSUBPSr213r:
21716   case X86::VFNMSUBSDr213r:
21717   case X86::VFNMSUBSSr213r:
21718   case X86::VFMADDSUBPDr213r:
21719   case X86::VFMADDSUBPSr213r:
21720   case X86::VFMSUBADDPDr213r:
21721   case X86::VFMSUBADDPSr213r:
21722   case X86::VFMADDPDr213rY:
21723   case X86::VFMADDPSr213rY:
21724   case X86::VFMSUBPDr213rY:
21725   case X86::VFMSUBPSr213rY:
21726   case X86::VFNMADDPDr213rY:
21727   case X86::VFNMADDPSr213rY:
21728   case X86::VFNMSUBPDr213rY:
21729   case X86::VFNMSUBPSr213rY:
21730   case X86::VFMADDSUBPDr213rY:
21731   case X86::VFMADDSUBPSr213rY:
21732   case X86::VFMSUBADDPDr213rY:
21733   case X86::VFMSUBADDPSr213rY:
21734     return emitFMA3Instr(MI, BB);
21735   }
21736 }
21737
21738 //===----------------------------------------------------------------------===//
21739 //                           X86 Optimization Hooks
21740 //===----------------------------------------------------------------------===//
21741
21742 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21743                                                       APInt &KnownZero,
21744                                                       APInt &KnownOne,
21745                                                       const SelectionDAG &DAG,
21746                                                       unsigned Depth) const {
21747   unsigned BitWidth = KnownZero.getBitWidth();
21748   unsigned Opc = Op.getOpcode();
21749   assert((Opc >= ISD::BUILTIN_OP_END ||
21750           Opc == ISD::INTRINSIC_WO_CHAIN ||
21751           Opc == ISD::INTRINSIC_W_CHAIN ||
21752           Opc == ISD::INTRINSIC_VOID) &&
21753          "Should use MaskedValueIsZero if you don't know whether Op"
21754          " is a target node!");
21755
21756   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21757   switch (Opc) {
21758   default: break;
21759   case X86ISD::ADD:
21760   case X86ISD::SUB:
21761   case X86ISD::ADC:
21762   case X86ISD::SBB:
21763   case X86ISD::SMUL:
21764   case X86ISD::UMUL:
21765   case X86ISD::INC:
21766   case X86ISD::DEC:
21767   case X86ISD::OR:
21768   case X86ISD::XOR:
21769   case X86ISD::AND:
21770     // These nodes' second result is a boolean.
21771     if (Op.getResNo() == 0)
21772       break;
21773     // Fallthrough
21774   case X86ISD::SETCC:
21775     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21776     break;
21777   case ISD::INTRINSIC_WO_CHAIN: {
21778     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21779     unsigned NumLoBits = 0;
21780     switch (IntId) {
21781     default: break;
21782     case Intrinsic::x86_sse_movmsk_ps:
21783     case Intrinsic::x86_avx_movmsk_ps_256:
21784     case Intrinsic::x86_sse2_movmsk_pd:
21785     case Intrinsic::x86_avx_movmsk_pd_256:
21786     case Intrinsic::x86_mmx_pmovmskb:
21787     case Intrinsic::x86_sse2_pmovmskb_128:
21788     case Intrinsic::x86_avx2_pmovmskb: {
21789       // High bits of movmskp{s|d}, pmovmskb are known zero.
21790       switch (IntId) {
21791         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21792         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21793         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21794         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21795         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21796         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21797         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21798         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21799       }
21800       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21801       break;
21802     }
21803     }
21804     break;
21805   }
21806   }
21807 }
21808
21809 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21810   SDValue Op,
21811   const SelectionDAG &,
21812   unsigned Depth) const {
21813   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21814   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21815     return Op.getValueType().getScalarType().getSizeInBits();
21816
21817   // Fallback case.
21818   return 1;
21819 }
21820
21821 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21822 /// node is a GlobalAddress + offset.
21823 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21824                                        const GlobalValue* &GA,
21825                                        int64_t &Offset) const {
21826   if (N->getOpcode() == X86ISD::Wrapper) {
21827     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21828       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21829       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21830       return true;
21831     }
21832   }
21833   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21834 }
21835
21836 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21837 /// same as extracting the high 128-bit part of 256-bit vector and then
21838 /// inserting the result into the low part of a new 256-bit vector
21839 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21840   EVT VT = SVOp->getValueType(0);
21841   unsigned NumElems = VT.getVectorNumElements();
21842
21843   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21844   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21845     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21846         SVOp->getMaskElt(j) >= 0)
21847       return false;
21848
21849   return true;
21850 }
21851
21852 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21853 /// same as extracting the low 128-bit part of 256-bit vector and then
21854 /// inserting the result into the high part of a new 256-bit vector
21855 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21856   EVT VT = SVOp->getValueType(0);
21857   unsigned NumElems = VT.getVectorNumElements();
21858
21859   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21860   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21861     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21862         SVOp->getMaskElt(j) >= 0)
21863       return false;
21864
21865   return true;
21866 }
21867
21868 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21869 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21870                                         TargetLowering::DAGCombinerInfo &DCI,
21871                                         const X86Subtarget* Subtarget) {
21872   SDLoc dl(N);
21873   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21874   SDValue V1 = SVOp->getOperand(0);
21875   SDValue V2 = SVOp->getOperand(1);
21876   EVT VT = SVOp->getValueType(0);
21877   unsigned NumElems = VT.getVectorNumElements();
21878
21879   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21880       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21881     //
21882     //                   0,0,0,...
21883     //                      |
21884     //    V      UNDEF    BUILD_VECTOR    UNDEF
21885     //     \      /           \           /
21886     //  CONCAT_VECTOR         CONCAT_VECTOR
21887     //         \                  /
21888     //          \                /
21889     //          RESULT: V + zero extended
21890     //
21891     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21892         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21893         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21894       return SDValue();
21895
21896     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21897       return SDValue();
21898
21899     // To match the shuffle mask, the first half of the mask should
21900     // be exactly the first vector, and all the rest a splat with the
21901     // first element of the second one.
21902     for (unsigned i = 0; i != NumElems/2; ++i)
21903       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21904           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21905         return SDValue();
21906
21907     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21908     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21909       if (Ld->hasNUsesOfValue(1, 0)) {
21910         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21911         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21912         SDValue ResNode =
21913           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21914                                   Ld->getMemoryVT(),
21915                                   Ld->getPointerInfo(),
21916                                   Ld->getAlignment(),
21917                                   false/*isVolatile*/, true/*ReadMem*/,
21918                                   false/*WriteMem*/);
21919
21920         // Make sure the newly-created LOAD is in the same position as Ld in
21921         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21922         // and update uses of Ld's output chain to use the TokenFactor.
21923         if (Ld->hasAnyUseOfValue(1)) {
21924           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21925                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21926           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21927           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21928                                  SDValue(ResNode.getNode(), 1));
21929         }
21930
21931         return DAG.getBitcast(VT, ResNode);
21932       }
21933     }
21934
21935     // Emit a zeroed vector and insert the desired subvector on its
21936     // first half.
21937     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21938     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21939     return DCI.CombineTo(N, InsV);
21940   }
21941
21942   //===--------------------------------------------------------------------===//
21943   // Combine some shuffles into subvector extracts and inserts:
21944   //
21945
21946   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21947   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21948     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21949     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21950     return DCI.CombineTo(N, InsV);
21951   }
21952
21953   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21954   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21955     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21956     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21957     return DCI.CombineTo(N, InsV);
21958   }
21959
21960   return SDValue();
21961 }
21962
21963 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21964 /// possible.
21965 ///
21966 /// This is the leaf of the recursive combinine below. When we have found some
21967 /// chain of single-use x86 shuffle instructions and accumulated the combined
21968 /// shuffle mask represented by them, this will try to pattern match that mask
21969 /// into either a single instruction if there is a special purpose instruction
21970 /// for this operation, or into a PSHUFB instruction which is a fully general
21971 /// instruction but should only be used to replace chains over a certain depth.
21972 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21973                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21974                                    TargetLowering::DAGCombinerInfo &DCI,
21975                                    const X86Subtarget *Subtarget) {
21976   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21977
21978   // Find the operand that enters the chain. Note that multiple uses are OK
21979   // here, we're not going to remove the operand we find.
21980   SDValue Input = Op.getOperand(0);
21981   while (Input.getOpcode() == ISD::BITCAST)
21982     Input = Input.getOperand(0);
21983
21984   MVT VT = Input.getSimpleValueType();
21985   MVT RootVT = Root.getSimpleValueType();
21986   SDLoc DL(Root);
21987
21988   // Just remove no-op shuffle masks.
21989   if (Mask.size() == 1) {
21990     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21991                   /*AddTo*/ true);
21992     return true;
21993   }
21994
21995   // Use the float domain if the operand type is a floating point type.
21996   bool FloatDomain = VT.isFloatingPoint();
21997
21998   // For floating point shuffles, we don't have free copies in the shuffle
21999   // instructions or the ability to load as part of the instruction, so
22000   // canonicalize their shuffles to UNPCK or MOV variants.
22001   //
22002   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22003   // vectors because it can have a load folded into it that UNPCK cannot. This
22004   // doesn't preclude something switching to the shorter encoding post-RA.
22005   //
22006   // FIXME: Should teach these routines about AVX vector widths.
22007   if (FloatDomain && VT.getSizeInBits() == 128) {
22008     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22009       bool Lo = Mask.equals({0, 0});
22010       unsigned Shuffle;
22011       MVT ShuffleVT;
22012       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22013       // is no slower than UNPCKLPD but has the option to fold the input operand
22014       // into even an unaligned memory load.
22015       if (Lo && Subtarget->hasSSE3()) {
22016         Shuffle = X86ISD::MOVDDUP;
22017         ShuffleVT = MVT::v2f64;
22018       } else {
22019         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22020         // than the UNPCK variants.
22021         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22022         ShuffleVT = MVT::v4f32;
22023       }
22024       if (Depth == 1 && Root->getOpcode() == Shuffle)
22025         return false; // Nothing to do!
22026       Op = DAG.getBitcast(ShuffleVT, Input);
22027       DCI.AddToWorklist(Op.getNode());
22028       if (Shuffle == X86ISD::MOVDDUP)
22029         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22030       else
22031         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22032       DCI.AddToWorklist(Op.getNode());
22033       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22034                     /*AddTo*/ true);
22035       return true;
22036     }
22037     if (Subtarget->hasSSE3() &&
22038         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22039       bool Lo = Mask.equals({0, 0, 2, 2});
22040       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22041       MVT ShuffleVT = MVT::v4f32;
22042       if (Depth == 1 && Root->getOpcode() == Shuffle)
22043         return false; // Nothing to do!
22044       Op = DAG.getBitcast(ShuffleVT, Input);
22045       DCI.AddToWorklist(Op.getNode());
22046       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22047       DCI.AddToWorklist(Op.getNode());
22048       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22049                     /*AddTo*/ true);
22050       return true;
22051     }
22052     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22053       bool Lo = Mask.equals({0, 0, 1, 1});
22054       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22055       MVT ShuffleVT = MVT::v4f32;
22056       if (Depth == 1 && Root->getOpcode() == Shuffle)
22057         return false; // Nothing to do!
22058       Op = DAG.getBitcast(ShuffleVT, Input);
22059       DCI.AddToWorklist(Op.getNode());
22060       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22061       DCI.AddToWorklist(Op.getNode());
22062       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22063                     /*AddTo*/ true);
22064       return true;
22065     }
22066   }
22067
22068   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22069   // variants as none of these have single-instruction variants that are
22070   // superior to the UNPCK formulation.
22071   if (!FloatDomain && VT.getSizeInBits() == 128 &&
22072       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22073        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22074        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22075        Mask.equals(
22076            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22077     bool Lo = Mask[0] == 0;
22078     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22079     if (Depth == 1 && Root->getOpcode() == Shuffle)
22080       return false; // Nothing to do!
22081     MVT ShuffleVT;
22082     switch (Mask.size()) {
22083     case 8:
22084       ShuffleVT = MVT::v8i16;
22085       break;
22086     case 16:
22087       ShuffleVT = MVT::v16i8;
22088       break;
22089     default:
22090       llvm_unreachable("Impossible mask size!");
22091     };
22092     Op = DAG.getBitcast(ShuffleVT, Input);
22093     DCI.AddToWorklist(Op.getNode());
22094     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22095     DCI.AddToWorklist(Op.getNode());
22096     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22097                   /*AddTo*/ true);
22098     return true;
22099   }
22100
22101   // Don't try to re-form single instruction chains under any circumstances now
22102   // that we've done encoding canonicalization for them.
22103   if (Depth < 2)
22104     return false;
22105
22106   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22107   // can replace them with a single PSHUFB instruction profitably. Intel's
22108   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22109   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22110   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22111     SmallVector<SDValue, 16> PSHUFBMask;
22112     int NumBytes = VT.getSizeInBits() / 8;
22113     int Ratio = NumBytes / Mask.size();
22114     for (int i = 0; i < NumBytes; ++i) {
22115       if (Mask[i / Ratio] == SM_SentinelUndef) {
22116         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22117         continue;
22118       }
22119       int M = Mask[i / Ratio] != SM_SentinelZero
22120                   ? Ratio * Mask[i / Ratio] + i % Ratio
22121                   : 255;
22122       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22123     }
22124     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22125     Op = DAG.getBitcast(ByteVT, Input);
22126     DCI.AddToWorklist(Op.getNode());
22127     SDValue PSHUFBMaskOp =
22128         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22129     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22130     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22131     DCI.AddToWorklist(Op.getNode());
22132     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22133                   /*AddTo*/ true);
22134     return true;
22135   }
22136
22137   // Failed to find any combines.
22138   return false;
22139 }
22140
22141 /// \brief Fully generic combining of x86 shuffle instructions.
22142 ///
22143 /// This should be the last combine run over the x86 shuffle instructions. Once
22144 /// they have been fully optimized, this will recursively consider all chains
22145 /// of single-use shuffle instructions, build a generic model of the cumulative
22146 /// shuffle operation, and check for simpler instructions which implement this
22147 /// operation. We use this primarily for two purposes:
22148 ///
22149 /// 1) Collapse generic shuffles to specialized single instructions when
22150 ///    equivalent. In most cases, this is just an encoding size win, but
22151 ///    sometimes we will collapse multiple generic shuffles into a single
22152 ///    special-purpose shuffle.
22153 /// 2) Look for sequences of shuffle instructions with 3 or more total
22154 ///    instructions, and replace them with the slightly more expensive SSSE3
22155 ///    PSHUFB instruction if available. We do this as the last combining step
22156 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22157 ///    a suitable short sequence of other instructions. The PHUFB will either
22158 ///    use a register or have to read from memory and so is slightly (but only
22159 ///    slightly) more expensive than the other shuffle instructions.
22160 ///
22161 /// Because this is inherently a quadratic operation (for each shuffle in
22162 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22163 /// This should never be an issue in practice as the shuffle lowering doesn't
22164 /// produce sequences of more than 8 instructions.
22165 ///
22166 /// FIXME: We will currently miss some cases where the redundant shuffling
22167 /// would simplify under the threshold for PSHUFB formation because of
22168 /// combine-ordering. To fix this, we should do the redundant instruction
22169 /// combining in this recursive walk.
22170 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22171                                           ArrayRef<int> RootMask,
22172                                           int Depth, bool HasPSHUFB,
22173                                           SelectionDAG &DAG,
22174                                           TargetLowering::DAGCombinerInfo &DCI,
22175                                           const X86Subtarget *Subtarget) {
22176   // Bound the depth of our recursive combine because this is ultimately
22177   // quadratic in nature.
22178   if (Depth > 8)
22179     return false;
22180
22181   // Directly rip through bitcasts to find the underlying operand.
22182   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22183     Op = Op.getOperand(0);
22184
22185   MVT VT = Op.getSimpleValueType();
22186   if (!VT.isVector())
22187     return false; // Bail if we hit a non-vector.
22188
22189   assert(Root.getSimpleValueType().isVector() &&
22190          "Shuffles operate on vector types!");
22191   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22192          "Can only combine shuffles of the same vector register size.");
22193
22194   if (!isTargetShuffle(Op.getOpcode()))
22195     return false;
22196   SmallVector<int, 16> OpMask;
22197   bool IsUnary;
22198   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22199   // We only can combine unary shuffles which we can decode the mask for.
22200   if (!HaveMask || !IsUnary)
22201     return false;
22202
22203   assert(VT.getVectorNumElements() == OpMask.size() &&
22204          "Different mask size from vector size!");
22205   assert(((RootMask.size() > OpMask.size() &&
22206            RootMask.size() % OpMask.size() == 0) ||
22207           (OpMask.size() > RootMask.size() &&
22208            OpMask.size() % RootMask.size() == 0) ||
22209           OpMask.size() == RootMask.size()) &&
22210          "The smaller number of elements must divide the larger.");
22211   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22212   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22213   assert(((RootRatio == 1 && OpRatio == 1) ||
22214           (RootRatio == 1) != (OpRatio == 1)) &&
22215          "Must not have a ratio for both incoming and op masks!");
22216
22217   SmallVector<int, 16> Mask;
22218   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22219
22220   // Merge this shuffle operation's mask into our accumulated mask. Note that
22221   // this shuffle's mask will be the first applied to the input, followed by the
22222   // root mask to get us all the way to the root value arrangement. The reason
22223   // for this order is that we are recursing up the operation chain.
22224   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22225     int RootIdx = i / RootRatio;
22226     if (RootMask[RootIdx] < 0) {
22227       // This is a zero or undef lane, we're done.
22228       Mask.push_back(RootMask[RootIdx]);
22229       continue;
22230     }
22231
22232     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22233     int OpIdx = RootMaskedIdx / OpRatio;
22234     if (OpMask[OpIdx] < 0) {
22235       // The incoming lanes are zero or undef, it doesn't matter which ones we
22236       // are using.
22237       Mask.push_back(OpMask[OpIdx]);
22238       continue;
22239     }
22240
22241     // Ok, we have non-zero lanes, map them through.
22242     Mask.push_back(OpMask[OpIdx] * OpRatio +
22243                    RootMaskedIdx % OpRatio);
22244   }
22245
22246   // See if we can recurse into the operand to combine more things.
22247   switch (Op.getOpcode()) {
22248   case X86ISD::PSHUFB:
22249     HasPSHUFB = true;
22250   case X86ISD::PSHUFD:
22251   case X86ISD::PSHUFHW:
22252   case X86ISD::PSHUFLW:
22253     if (Op.getOperand(0).hasOneUse() &&
22254         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22255                                       HasPSHUFB, DAG, DCI, Subtarget))
22256       return true;
22257     break;
22258
22259   case X86ISD::UNPCKL:
22260   case X86ISD::UNPCKH:
22261     assert(Op.getOperand(0) == Op.getOperand(1) &&
22262            "We only combine unary shuffles!");
22263     // We can't check for single use, we have to check that this shuffle is the
22264     // only user.
22265     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22266         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22267                                       HasPSHUFB, DAG, DCI, Subtarget))
22268       return true;
22269     break;
22270   }
22271
22272   // Minor canonicalization of the accumulated shuffle mask to make it easier
22273   // to match below. All this does is detect masks with squential pairs of
22274   // elements, and shrink them to the half-width mask. It does this in a loop
22275   // so it will reduce the size of the mask to the minimal width mask which
22276   // performs an equivalent shuffle.
22277   SmallVector<int, 16> WidenedMask;
22278   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22279     Mask = std::move(WidenedMask);
22280     WidenedMask.clear();
22281   }
22282
22283   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22284                                 Subtarget);
22285 }
22286
22287 /// \brief Get the PSHUF-style mask from PSHUF node.
22288 ///
22289 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22290 /// PSHUF-style masks that can be reused with such instructions.
22291 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22292   MVT VT = N.getSimpleValueType();
22293   SmallVector<int, 4> Mask;
22294   bool IsUnary;
22295   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22296   (void)HaveMask;
22297   assert(HaveMask);
22298
22299   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22300   // matter. Check that the upper masks are repeats and remove them.
22301   if (VT.getSizeInBits() > 128) {
22302     int LaneElts = 128 / VT.getScalarSizeInBits();
22303 #ifndef NDEBUG
22304     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22305       for (int j = 0; j < LaneElts; ++j)
22306         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22307                "Mask doesn't repeat in high 128-bit lanes!");
22308 #endif
22309     Mask.resize(LaneElts);
22310   }
22311
22312   switch (N.getOpcode()) {
22313   case X86ISD::PSHUFD:
22314     return Mask;
22315   case X86ISD::PSHUFLW:
22316     Mask.resize(4);
22317     return Mask;
22318   case X86ISD::PSHUFHW:
22319     Mask.erase(Mask.begin(), Mask.begin() + 4);
22320     for (int &M : Mask)
22321       M -= 4;
22322     return Mask;
22323   default:
22324     llvm_unreachable("No valid shuffle instruction found!");
22325   }
22326 }
22327
22328 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22329 ///
22330 /// We walk up the chain and look for a combinable shuffle, skipping over
22331 /// shuffles that we could hoist this shuffle's transformation past without
22332 /// altering anything.
22333 static SDValue
22334 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22335                              SelectionDAG &DAG,
22336                              TargetLowering::DAGCombinerInfo &DCI) {
22337   assert(N.getOpcode() == X86ISD::PSHUFD &&
22338          "Called with something other than an x86 128-bit half shuffle!");
22339   SDLoc DL(N);
22340
22341   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22342   // of the shuffles in the chain so that we can form a fresh chain to replace
22343   // this one.
22344   SmallVector<SDValue, 8> Chain;
22345   SDValue V = N.getOperand(0);
22346   for (; V.hasOneUse(); V = V.getOperand(0)) {
22347     switch (V.getOpcode()) {
22348     default:
22349       return SDValue(); // Nothing combined!
22350
22351     case ISD::BITCAST:
22352       // Skip bitcasts as we always know the type for the target specific
22353       // instructions.
22354       continue;
22355
22356     case X86ISD::PSHUFD:
22357       // Found another dword shuffle.
22358       break;
22359
22360     case X86ISD::PSHUFLW:
22361       // Check that the low words (being shuffled) are the identity in the
22362       // dword shuffle, and the high words are self-contained.
22363       if (Mask[0] != 0 || Mask[1] != 1 ||
22364           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22365         return SDValue();
22366
22367       Chain.push_back(V);
22368       continue;
22369
22370     case X86ISD::PSHUFHW:
22371       // Check that the high words (being shuffled) are the identity in the
22372       // dword shuffle, and the low words are self-contained.
22373       if (Mask[2] != 2 || Mask[3] != 3 ||
22374           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22375         return SDValue();
22376
22377       Chain.push_back(V);
22378       continue;
22379
22380     case X86ISD::UNPCKL:
22381     case X86ISD::UNPCKH:
22382       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22383       // shuffle into a preceding word shuffle.
22384       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22385           V.getSimpleValueType().getScalarType() != MVT::i16)
22386         return SDValue();
22387
22388       // Search for a half-shuffle which we can combine with.
22389       unsigned CombineOp =
22390           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22391       if (V.getOperand(0) != V.getOperand(1) ||
22392           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22393         return SDValue();
22394       Chain.push_back(V);
22395       V = V.getOperand(0);
22396       do {
22397         switch (V.getOpcode()) {
22398         default:
22399           return SDValue(); // Nothing to combine.
22400
22401         case X86ISD::PSHUFLW:
22402         case X86ISD::PSHUFHW:
22403           if (V.getOpcode() == CombineOp)
22404             break;
22405
22406           Chain.push_back(V);
22407
22408           // Fallthrough!
22409         case ISD::BITCAST:
22410           V = V.getOperand(0);
22411           continue;
22412         }
22413         break;
22414       } while (V.hasOneUse());
22415       break;
22416     }
22417     // Break out of the loop if we break out of the switch.
22418     break;
22419   }
22420
22421   if (!V.hasOneUse())
22422     // We fell out of the loop without finding a viable combining instruction.
22423     return SDValue();
22424
22425   // Merge this node's mask and our incoming mask.
22426   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22427   for (int &M : Mask)
22428     M = VMask[M];
22429   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22430                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22431
22432   // Rebuild the chain around this new shuffle.
22433   while (!Chain.empty()) {
22434     SDValue W = Chain.pop_back_val();
22435
22436     if (V.getValueType() != W.getOperand(0).getValueType())
22437       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22438
22439     switch (W.getOpcode()) {
22440     default:
22441       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22442
22443     case X86ISD::UNPCKL:
22444     case X86ISD::UNPCKH:
22445       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22446       break;
22447
22448     case X86ISD::PSHUFD:
22449     case X86ISD::PSHUFLW:
22450     case X86ISD::PSHUFHW:
22451       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22452       break;
22453     }
22454   }
22455   if (V.getValueType() != N.getValueType())
22456     V = DAG.getBitcast(N.getValueType(), V);
22457
22458   // Return the new chain to replace N.
22459   return V;
22460 }
22461
22462 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22463 /// pshufhw.
22464 ///
22465 /// We walk up the chain, skipping shuffles of the other half and looking
22466 /// through shuffles which switch halves trying to find a shuffle of the same
22467 /// pair of dwords.
22468 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22469                                         SelectionDAG &DAG,
22470                                         TargetLowering::DAGCombinerInfo &DCI) {
22471   assert(
22472       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22473       "Called with something other than an x86 128-bit half shuffle!");
22474   SDLoc DL(N);
22475   unsigned CombineOpcode = N.getOpcode();
22476
22477   // Walk up a single-use chain looking for a combinable shuffle.
22478   SDValue V = N.getOperand(0);
22479   for (; V.hasOneUse(); V = V.getOperand(0)) {
22480     switch (V.getOpcode()) {
22481     default:
22482       return false; // Nothing combined!
22483
22484     case ISD::BITCAST:
22485       // Skip bitcasts as we always know the type for the target specific
22486       // instructions.
22487       continue;
22488
22489     case X86ISD::PSHUFLW:
22490     case X86ISD::PSHUFHW:
22491       if (V.getOpcode() == CombineOpcode)
22492         break;
22493
22494       // Other-half shuffles are no-ops.
22495       continue;
22496     }
22497     // Break out of the loop if we break out of the switch.
22498     break;
22499   }
22500
22501   if (!V.hasOneUse())
22502     // We fell out of the loop without finding a viable combining instruction.
22503     return false;
22504
22505   // Combine away the bottom node as its shuffle will be accumulated into
22506   // a preceding shuffle.
22507   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22508
22509   // Record the old value.
22510   SDValue Old = V;
22511
22512   // Merge this node's mask and our incoming mask (adjusted to account for all
22513   // the pshufd instructions encountered).
22514   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22515   for (int &M : Mask)
22516     M = VMask[M];
22517   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22518                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22519
22520   // Check that the shuffles didn't cancel each other out. If not, we need to
22521   // combine to the new one.
22522   if (Old != V)
22523     // Replace the combinable shuffle with the combined one, updating all users
22524     // so that we re-evaluate the chain here.
22525     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22526
22527   return true;
22528 }
22529
22530 /// \brief Try to combine x86 target specific shuffles.
22531 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22532                                            TargetLowering::DAGCombinerInfo &DCI,
22533                                            const X86Subtarget *Subtarget) {
22534   SDLoc DL(N);
22535   MVT VT = N.getSimpleValueType();
22536   SmallVector<int, 4> Mask;
22537
22538   switch (N.getOpcode()) {
22539   case X86ISD::PSHUFD:
22540   case X86ISD::PSHUFLW:
22541   case X86ISD::PSHUFHW:
22542     Mask = getPSHUFShuffleMask(N);
22543     assert(Mask.size() == 4);
22544     break;
22545   default:
22546     return SDValue();
22547   }
22548
22549   // Nuke no-op shuffles that show up after combining.
22550   if (isNoopShuffleMask(Mask))
22551     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22552
22553   // Look for simplifications involving one or two shuffle instructions.
22554   SDValue V = N.getOperand(0);
22555   switch (N.getOpcode()) {
22556   default:
22557     break;
22558   case X86ISD::PSHUFLW:
22559   case X86ISD::PSHUFHW:
22560     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22561
22562     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22563       return SDValue(); // We combined away this shuffle, so we're done.
22564
22565     // See if this reduces to a PSHUFD which is no more expensive and can
22566     // combine with more operations. Note that it has to at least flip the
22567     // dwords as otherwise it would have been removed as a no-op.
22568     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22569       int DMask[] = {0, 1, 2, 3};
22570       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22571       DMask[DOffset + 0] = DOffset + 1;
22572       DMask[DOffset + 1] = DOffset + 0;
22573       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22574       V = DAG.getBitcast(DVT, V);
22575       DCI.AddToWorklist(V.getNode());
22576       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22577                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22578       DCI.AddToWorklist(V.getNode());
22579       return DAG.getBitcast(VT, V);
22580     }
22581
22582     // Look for shuffle patterns which can be implemented as a single unpack.
22583     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22584     // only works when we have a PSHUFD followed by two half-shuffles.
22585     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22586         (V.getOpcode() == X86ISD::PSHUFLW ||
22587          V.getOpcode() == X86ISD::PSHUFHW) &&
22588         V.getOpcode() != N.getOpcode() &&
22589         V.hasOneUse()) {
22590       SDValue D = V.getOperand(0);
22591       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22592         D = D.getOperand(0);
22593       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22594         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22595         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22596         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22597         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22598         int WordMask[8];
22599         for (int i = 0; i < 4; ++i) {
22600           WordMask[i + NOffset] = Mask[i] + NOffset;
22601           WordMask[i + VOffset] = VMask[i] + VOffset;
22602         }
22603         // Map the word mask through the DWord mask.
22604         int MappedMask[8];
22605         for (int i = 0; i < 8; ++i)
22606           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22607         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22608             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22609           // We can replace all three shuffles with an unpack.
22610           V = DAG.getBitcast(VT, D.getOperand(0));
22611           DCI.AddToWorklist(V.getNode());
22612           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22613                                                 : X86ISD::UNPCKH,
22614                              DL, VT, V, V);
22615         }
22616       }
22617     }
22618
22619     break;
22620
22621   case X86ISD::PSHUFD:
22622     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22623       return NewN;
22624
22625     break;
22626   }
22627
22628   return SDValue();
22629 }
22630
22631 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22632 ///
22633 /// We combine this directly on the abstract vector shuffle nodes so it is
22634 /// easier to generically match. We also insert dummy vector shuffle nodes for
22635 /// the operands which explicitly discard the lanes which are unused by this
22636 /// operation to try to flow through the rest of the combiner the fact that
22637 /// they're unused.
22638 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22639   SDLoc DL(N);
22640   EVT VT = N->getValueType(0);
22641
22642   // We only handle target-independent shuffles.
22643   // FIXME: It would be easy and harmless to use the target shuffle mask
22644   // extraction tool to support more.
22645   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22646     return SDValue();
22647
22648   auto *SVN = cast<ShuffleVectorSDNode>(N);
22649   ArrayRef<int> Mask = SVN->getMask();
22650   SDValue V1 = N->getOperand(0);
22651   SDValue V2 = N->getOperand(1);
22652
22653   // We require the first shuffle operand to be the SUB node, and the second to
22654   // be the ADD node.
22655   // FIXME: We should support the commuted patterns.
22656   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22657     return SDValue();
22658
22659   // If there are other uses of these operations we can't fold them.
22660   if (!V1->hasOneUse() || !V2->hasOneUse())
22661     return SDValue();
22662
22663   // Ensure that both operations have the same operands. Note that we can
22664   // commute the FADD operands.
22665   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22666   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22667       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22668     return SDValue();
22669
22670   // We're looking for blends between FADD and FSUB nodes. We insist on these
22671   // nodes being lined up in a specific expected pattern.
22672   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22673         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22674         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22675     return SDValue();
22676
22677   // Only specific types are legal at this point, assert so we notice if and
22678   // when these change.
22679   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22680           VT == MVT::v4f64) &&
22681          "Unknown vector type encountered!");
22682
22683   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22684 }
22685
22686 /// PerformShuffleCombine - Performs several different shuffle combines.
22687 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22688                                      TargetLowering::DAGCombinerInfo &DCI,
22689                                      const X86Subtarget *Subtarget) {
22690   SDLoc dl(N);
22691   SDValue N0 = N->getOperand(0);
22692   SDValue N1 = N->getOperand(1);
22693   EVT VT = N->getValueType(0);
22694
22695   // Don't create instructions with illegal types after legalize types has run.
22696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22697   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22698     return SDValue();
22699
22700   // If we have legalized the vector types, look for blends of FADD and FSUB
22701   // nodes that we can fuse into an ADDSUB node.
22702   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22703     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22704       return AddSub;
22705
22706   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22707   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22708       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22709     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22710
22711   // During Type Legalization, when promoting illegal vector types,
22712   // the backend might introduce new shuffle dag nodes and bitcasts.
22713   //
22714   // This code performs the following transformation:
22715   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22716   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22717   //
22718   // We do this only if both the bitcast and the BINOP dag nodes have
22719   // one use. Also, perform this transformation only if the new binary
22720   // operation is legal. This is to avoid introducing dag nodes that
22721   // potentially need to be further expanded (or custom lowered) into a
22722   // less optimal sequence of dag nodes.
22723   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22724       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22725       N0.getOpcode() == ISD::BITCAST) {
22726     SDValue BC0 = N0.getOperand(0);
22727     EVT SVT = BC0.getValueType();
22728     unsigned Opcode = BC0.getOpcode();
22729     unsigned NumElts = VT.getVectorNumElements();
22730
22731     if (BC0.hasOneUse() && SVT.isVector() &&
22732         SVT.getVectorNumElements() * 2 == NumElts &&
22733         TLI.isOperationLegal(Opcode, VT)) {
22734       bool CanFold = false;
22735       switch (Opcode) {
22736       default : break;
22737       case ISD::ADD :
22738       case ISD::FADD :
22739       case ISD::SUB :
22740       case ISD::FSUB :
22741       case ISD::MUL :
22742       case ISD::FMUL :
22743         CanFold = true;
22744       }
22745
22746       unsigned SVTNumElts = SVT.getVectorNumElements();
22747       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22748       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22749         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22750       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22751         CanFold = SVOp->getMaskElt(i) < 0;
22752
22753       if (CanFold) {
22754         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22755         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22756         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22757         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22758       }
22759     }
22760   }
22761
22762   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22763   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22764   // consecutive, non-overlapping, and in the right order.
22765   SmallVector<SDValue, 16> Elts;
22766   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22767     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22768
22769   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22770     return LD;
22771
22772   if (isTargetShuffle(N->getOpcode())) {
22773     SDValue Shuffle =
22774         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22775     if (Shuffle.getNode())
22776       return Shuffle;
22777
22778     // Try recursively combining arbitrary sequences of x86 shuffle
22779     // instructions into higher-order shuffles. We do this after combining
22780     // specific PSHUF instruction sequences into their minimal form so that we
22781     // can evaluate how many specialized shuffle instructions are involved in
22782     // a particular chain.
22783     SmallVector<int, 1> NonceMask; // Just a placeholder.
22784     NonceMask.push_back(0);
22785     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22786                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22787                                       DCI, Subtarget))
22788       return SDValue(); // This routine will use CombineTo to replace N.
22789   }
22790
22791   return SDValue();
22792 }
22793
22794 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22795 /// specific shuffle of a load can be folded into a single element load.
22796 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22797 /// shuffles have been custom lowered so we need to handle those here.
22798 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22799                                          TargetLowering::DAGCombinerInfo &DCI) {
22800   if (DCI.isBeforeLegalizeOps())
22801     return SDValue();
22802
22803   SDValue InVec = N->getOperand(0);
22804   SDValue EltNo = N->getOperand(1);
22805
22806   if (!isa<ConstantSDNode>(EltNo))
22807     return SDValue();
22808
22809   EVT OriginalVT = InVec.getValueType();
22810
22811   if (InVec.getOpcode() == ISD::BITCAST) {
22812     // Don't duplicate a load with other uses.
22813     if (!InVec.hasOneUse())
22814       return SDValue();
22815     EVT BCVT = InVec.getOperand(0).getValueType();
22816     if (!BCVT.isVector() ||
22817         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22818       return SDValue();
22819     InVec = InVec.getOperand(0);
22820   }
22821
22822   EVT CurrentVT = InVec.getValueType();
22823
22824   if (!isTargetShuffle(InVec.getOpcode()))
22825     return SDValue();
22826
22827   // Don't duplicate a load with other uses.
22828   if (!InVec.hasOneUse())
22829     return SDValue();
22830
22831   SmallVector<int, 16> ShuffleMask;
22832   bool UnaryShuffle;
22833   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22834                             ShuffleMask, UnaryShuffle))
22835     return SDValue();
22836
22837   // Select the input vector, guarding against out of range extract vector.
22838   unsigned NumElems = CurrentVT.getVectorNumElements();
22839   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22840   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22841   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22842                                          : InVec.getOperand(1);
22843
22844   // If inputs to shuffle are the same for both ops, then allow 2 uses
22845   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22846                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22847
22848   if (LdNode.getOpcode() == ISD::BITCAST) {
22849     // Don't duplicate a load with other uses.
22850     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22851       return SDValue();
22852
22853     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22854     LdNode = LdNode.getOperand(0);
22855   }
22856
22857   if (!ISD::isNormalLoad(LdNode.getNode()))
22858     return SDValue();
22859
22860   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22861
22862   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22863     return SDValue();
22864
22865   EVT EltVT = N->getValueType(0);
22866   // If there's a bitcast before the shuffle, check if the load type and
22867   // alignment is valid.
22868   unsigned Align = LN0->getAlignment();
22869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22870   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22871       EltVT.getTypeForEVT(*DAG.getContext()));
22872
22873   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22874     return SDValue();
22875
22876   // All checks match so transform back to vector_shuffle so that DAG combiner
22877   // can finish the job
22878   SDLoc dl(N);
22879
22880   // Create shuffle node taking into account the case that its a unary shuffle
22881   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22882                                    : InVec.getOperand(1);
22883   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22884                                  InVec.getOperand(0), Shuffle,
22885                                  &ShuffleMask[0]);
22886   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22887   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22888                      EltNo);
22889 }
22890
22891 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22892 /// special and don't usually play with other vector types, it's better to
22893 /// handle them early to be sure we emit efficient code by avoiding
22894 /// store-load conversions.
22895 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22896   if (N->getValueType(0) != MVT::x86mmx ||
22897       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22898       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22899     return SDValue();
22900
22901   SDValue V = N->getOperand(0);
22902   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22903   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22904     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22905                        N->getValueType(0), V.getOperand(0));
22906
22907   return SDValue();
22908 }
22909
22910 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22911 /// generation and convert it from being a bunch of shuffles and extracts
22912 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22913 /// storing the value and loading scalars back, while for x64 we should
22914 /// use 64-bit extracts and shifts.
22915 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22916                                          TargetLowering::DAGCombinerInfo &DCI) {
22917   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22918     return NewOp;
22919
22920   SDValue InputVector = N->getOperand(0);
22921   SDLoc dl(InputVector);
22922   // Detect mmx to i32 conversion through a v2i32 elt extract.
22923   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22924       N->getValueType(0) == MVT::i32 &&
22925       InputVector.getValueType() == MVT::v2i32) {
22926
22927     // The bitcast source is a direct mmx result.
22928     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22929     if (MMXSrc.getValueType() == MVT::x86mmx)
22930       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22931                          N->getValueType(0),
22932                          InputVector.getNode()->getOperand(0));
22933
22934     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22935     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22936     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22937         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22938         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22939         MMXSrcOp.getValueType() == MVT::v1i64 &&
22940         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22941       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22942                          N->getValueType(0),
22943                          MMXSrcOp.getOperand(0));
22944   }
22945
22946   EVT VT = N->getValueType(0);
22947
22948   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22949       InputVector.getOpcode() == ISD::BITCAST &&
22950       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22951     uint64_t ExtractedElt =
22952         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22953     uint64_t InputValue =
22954         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22955     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22956     return DAG.getConstant(Res, dl, MVT::i1);
22957   }
22958   // Only operate on vectors of 4 elements, where the alternative shuffling
22959   // gets to be more expensive.
22960   if (InputVector.getValueType() != MVT::v4i32)
22961     return SDValue();
22962
22963   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22964   // single use which is a sign-extend or zero-extend, and all elements are
22965   // used.
22966   SmallVector<SDNode *, 4> Uses;
22967   unsigned ExtractedElements = 0;
22968   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22969        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22970     if (UI.getUse().getResNo() != InputVector.getResNo())
22971       return SDValue();
22972
22973     SDNode *Extract = *UI;
22974     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22975       return SDValue();
22976
22977     if (Extract->getValueType(0) != MVT::i32)
22978       return SDValue();
22979     if (!Extract->hasOneUse())
22980       return SDValue();
22981     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22982         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22983       return SDValue();
22984     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22985       return SDValue();
22986
22987     // Record which element was extracted.
22988     ExtractedElements |=
22989       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22990
22991     Uses.push_back(Extract);
22992   }
22993
22994   // If not all the elements were used, this may not be worthwhile.
22995   if (ExtractedElements != 15)
22996     return SDValue();
22997
22998   // Ok, we've now decided to do the transformation.
22999   // If 64-bit shifts are legal, use the extract-shift sequence,
23000   // otherwise bounce the vector off the cache.
23001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23002   SDValue Vals[4];
23003
23004   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23005     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23006     auto &DL = DAG.getDataLayout();
23007     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23008     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23009       DAG.getConstant(0, dl, VecIdxTy));
23010     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23011       DAG.getConstant(1, dl, VecIdxTy));
23012
23013     SDValue ShAmt = DAG.getConstant(
23014         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23015     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23016     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23017       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23018     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23019     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23020       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23021   } else {
23022     // Store the value to a temporary stack slot.
23023     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23024     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23025       MachinePointerInfo(), false, false, 0);
23026
23027     EVT ElementType = InputVector.getValueType().getVectorElementType();
23028     unsigned EltSize = ElementType.getSizeInBits() / 8;
23029
23030     // Replace each use (extract) with a load of the appropriate element.
23031     for (unsigned i = 0; i < 4; ++i) {
23032       uint64_t Offset = EltSize * i;
23033       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23034       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23035
23036       SDValue ScalarAddr =
23037           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23038
23039       // Load the scalar.
23040       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23041                             ScalarAddr, MachinePointerInfo(),
23042                             false, false, false, 0);
23043
23044     }
23045   }
23046
23047   // Replace the extracts
23048   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23049     UE = Uses.end(); UI != UE; ++UI) {
23050     SDNode *Extract = *UI;
23051
23052     SDValue Idx = Extract->getOperand(1);
23053     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23054     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23055   }
23056
23057   // The replacement was made in place; don't return anything.
23058   return SDValue();
23059 }
23060
23061 static SDValue
23062 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23063                                       const X86Subtarget *Subtarget) {
23064   SDLoc dl(N);
23065   SDValue Cond = N->getOperand(0);
23066   SDValue LHS = N->getOperand(1);
23067   SDValue RHS = N->getOperand(2);
23068
23069   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23070     SDValue CondSrc = Cond->getOperand(0);
23071     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23072       Cond = CondSrc->getOperand(0);
23073   }
23074
23075   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23076     return SDValue();
23077
23078   // A vselect where all conditions and data are constants can be optimized into
23079   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23080   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23081       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23082     return SDValue();
23083
23084   unsigned MaskValue = 0;
23085   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23086     return SDValue();
23087
23088   MVT VT = N->getSimpleValueType(0);
23089   unsigned NumElems = VT.getVectorNumElements();
23090   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23091   for (unsigned i = 0; i < NumElems; ++i) {
23092     // Be sure we emit undef where we can.
23093     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23094       ShuffleMask[i] = -1;
23095     else
23096       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23097   }
23098
23099   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23100   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23101     return SDValue();
23102   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23103 }
23104
23105 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23106 /// nodes.
23107 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23108                                     TargetLowering::DAGCombinerInfo &DCI,
23109                                     const X86Subtarget *Subtarget) {
23110   SDLoc DL(N);
23111   SDValue Cond = N->getOperand(0);
23112   // Get the LHS/RHS of the select.
23113   SDValue LHS = N->getOperand(1);
23114   SDValue RHS = N->getOperand(2);
23115   EVT VT = LHS.getValueType();
23116   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23117
23118   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23119   // instructions match the semantics of the common C idiom x<y?x:y but not
23120   // x<=y?x:y, because of how they handle negative zero (which can be
23121   // ignored in unsafe-math mode).
23122   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23123   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23124       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23125       (Subtarget->hasSSE2() ||
23126        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23127     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23128
23129     unsigned Opcode = 0;
23130     // Check for x CC y ? x : y.
23131     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23132         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23133       switch (CC) {
23134       default: break;
23135       case ISD::SETULT:
23136         // Converting this to a min would handle NaNs incorrectly, and swapping
23137         // the operands would cause it to handle comparisons between positive
23138         // and negative zero incorrectly.
23139         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23140           if (!DAG.getTarget().Options.UnsafeFPMath &&
23141               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23142             break;
23143           std::swap(LHS, RHS);
23144         }
23145         Opcode = X86ISD::FMIN;
23146         break;
23147       case ISD::SETOLE:
23148         // Converting this to a min would handle comparisons between positive
23149         // and negative zero incorrectly.
23150         if (!DAG.getTarget().Options.UnsafeFPMath &&
23151             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23152           break;
23153         Opcode = X86ISD::FMIN;
23154         break;
23155       case ISD::SETULE:
23156         // Converting this to a min would handle both negative zeros and NaNs
23157         // incorrectly, but we can swap the operands to fix both.
23158         std::swap(LHS, RHS);
23159       case ISD::SETOLT:
23160       case ISD::SETLT:
23161       case ISD::SETLE:
23162         Opcode = X86ISD::FMIN;
23163         break;
23164
23165       case ISD::SETOGE:
23166         // Converting this to a max would handle comparisons between positive
23167         // and negative zero incorrectly.
23168         if (!DAG.getTarget().Options.UnsafeFPMath &&
23169             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23170           break;
23171         Opcode = X86ISD::FMAX;
23172         break;
23173       case ISD::SETUGT:
23174         // Converting this to a max would handle NaNs incorrectly, and swapping
23175         // the operands would cause it to handle comparisons between positive
23176         // and negative zero incorrectly.
23177         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23178           if (!DAG.getTarget().Options.UnsafeFPMath &&
23179               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23180             break;
23181           std::swap(LHS, RHS);
23182         }
23183         Opcode = X86ISD::FMAX;
23184         break;
23185       case ISD::SETUGE:
23186         // Converting this to a max would handle both negative zeros and NaNs
23187         // incorrectly, but we can swap the operands to fix both.
23188         std::swap(LHS, RHS);
23189       case ISD::SETOGT:
23190       case ISD::SETGT:
23191       case ISD::SETGE:
23192         Opcode = X86ISD::FMAX;
23193         break;
23194       }
23195     // Check for x CC y ? y : x -- a min/max with reversed arms.
23196     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23197                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23198       switch (CC) {
23199       default: break;
23200       case ISD::SETOGE:
23201         // Converting this to a min would handle comparisons between positive
23202         // and negative zero incorrectly, and swapping the operands would
23203         // cause it to handle NaNs incorrectly.
23204         if (!DAG.getTarget().Options.UnsafeFPMath &&
23205             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23206           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23207             break;
23208           std::swap(LHS, RHS);
23209         }
23210         Opcode = X86ISD::FMIN;
23211         break;
23212       case ISD::SETUGT:
23213         // Converting this to a min would handle NaNs incorrectly.
23214         if (!DAG.getTarget().Options.UnsafeFPMath &&
23215             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23216           break;
23217         Opcode = X86ISD::FMIN;
23218         break;
23219       case ISD::SETUGE:
23220         // Converting this to a min would handle both negative zeros and NaNs
23221         // incorrectly, but we can swap the operands to fix both.
23222         std::swap(LHS, RHS);
23223       case ISD::SETOGT:
23224       case ISD::SETGT:
23225       case ISD::SETGE:
23226         Opcode = X86ISD::FMIN;
23227         break;
23228
23229       case ISD::SETULT:
23230         // Converting this to a max would handle NaNs incorrectly.
23231         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23232           break;
23233         Opcode = X86ISD::FMAX;
23234         break;
23235       case ISD::SETOLE:
23236         // Converting this to a max would handle comparisons between positive
23237         // and negative zero incorrectly, and swapping the operands would
23238         // cause it to handle NaNs incorrectly.
23239         if (!DAG.getTarget().Options.UnsafeFPMath &&
23240             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23241           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23242             break;
23243           std::swap(LHS, RHS);
23244         }
23245         Opcode = X86ISD::FMAX;
23246         break;
23247       case ISD::SETULE:
23248         // Converting this to a max would handle both negative zeros and NaNs
23249         // incorrectly, but we can swap the operands to fix both.
23250         std::swap(LHS, RHS);
23251       case ISD::SETOLT:
23252       case ISD::SETLT:
23253       case ISD::SETLE:
23254         Opcode = X86ISD::FMAX;
23255         break;
23256       }
23257     }
23258
23259     if (Opcode)
23260       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23261   }
23262
23263   EVT CondVT = Cond.getValueType();
23264   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23265       CondVT.getVectorElementType() == MVT::i1) {
23266     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23267     // lowering on KNL. In this case we convert it to
23268     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23269     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23270     // Since SKX these selects have a proper lowering.
23271     EVT OpVT = LHS.getValueType();
23272     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23273         (OpVT.getVectorElementType() == MVT::i8 ||
23274          OpVT.getVectorElementType() == MVT::i16) &&
23275         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23276       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23277       DCI.AddToWorklist(Cond.getNode());
23278       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23279     }
23280   }
23281   // If this is a select between two integer constants, try to do some
23282   // optimizations.
23283   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23284     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23285       // Don't do this for crazy integer types.
23286       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23287         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23288         // so that TrueC (the true value) is larger than FalseC.
23289         bool NeedsCondInvert = false;
23290
23291         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23292             // Efficiently invertible.
23293             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23294              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23295               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23296           NeedsCondInvert = true;
23297           std::swap(TrueC, FalseC);
23298         }
23299
23300         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23301         if (FalseC->getAPIntValue() == 0 &&
23302             TrueC->getAPIntValue().isPowerOf2()) {
23303           if (NeedsCondInvert) // Invert the condition if needed.
23304             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23305                                DAG.getConstant(1, DL, Cond.getValueType()));
23306
23307           // Zero extend the condition if needed.
23308           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23309
23310           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23311           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23312                              DAG.getConstant(ShAmt, DL, MVT::i8));
23313         }
23314
23315         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23316         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23317           if (NeedsCondInvert) // Invert the condition if needed.
23318             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23319                                DAG.getConstant(1, DL, Cond.getValueType()));
23320
23321           // Zero extend the condition if needed.
23322           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23323                              FalseC->getValueType(0), Cond);
23324           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23325                              SDValue(FalseC, 0));
23326         }
23327
23328         // Optimize cases that will turn into an LEA instruction.  This requires
23329         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23330         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23331           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23332           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23333
23334           bool isFastMultiplier = false;
23335           if (Diff < 10) {
23336             switch ((unsigned char)Diff) {
23337               default: break;
23338               case 1:  // result = add base, cond
23339               case 2:  // result = lea base(    , cond*2)
23340               case 3:  // result = lea base(cond, cond*2)
23341               case 4:  // result = lea base(    , cond*4)
23342               case 5:  // result = lea base(cond, cond*4)
23343               case 8:  // result = lea base(    , cond*8)
23344               case 9:  // result = lea base(cond, cond*8)
23345                 isFastMultiplier = true;
23346                 break;
23347             }
23348           }
23349
23350           if (isFastMultiplier) {
23351             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23352             if (NeedsCondInvert) // Invert the condition if needed.
23353               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23354                                  DAG.getConstant(1, DL, Cond.getValueType()));
23355
23356             // Zero extend the condition if needed.
23357             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23358                                Cond);
23359             // Scale the condition by the difference.
23360             if (Diff != 1)
23361               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23362                                  DAG.getConstant(Diff, DL,
23363                                                  Cond.getValueType()));
23364
23365             // Add the base if non-zero.
23366             if (FalseC->getAPIntValue() != 0)
23367               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23368                                  SDValue(FalseC, 0));
23369             return Cond;
23370           }
23371         }
23372       }
23373   }
23374
23375   // Canonicalize max and min:
23376   // (x > y) ? x : y -> (x >= y) ? x : y
23377   // (x < y) ? x : y -> (x <= y) ? x : y
23378   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23379   // the need for an extra compare
23380   // against zero. e.g.
23381   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23382   // subl   %esi, %edi
23383   // testl  %edi, %edi
23384   // movl   $0, %eax
23385   // cmovgl %edi, %eax
23386   // =>
23387   // xorl   %eax, %eax
23388   // subl   %esi, $edi
23389   // cmovsl %eax, %edi
23390   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23391       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23392       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23393     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23394     switch (CC) {
23395     default: break;
23396     case ISD::SETLT:
23397     case ISD::SETGT: {
23398       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23399       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23400                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23401       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23402     }
23403     }
23404   }
23405
23406   // Early exit check
23407   if (!TLI.isTypeLegal(VT))
23408     return SDValue();
23409
23410   // Match VSELECTs into subs with unsigned saturation.
23411   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23412       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23413       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23414        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23415     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23416
23417     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23418     // left side invert the predicate to simplify logic below.
23419     SDValue Other;
23420     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23421       Other = RHS;
23422       CC = ISD::getSetCCInverse(CC, true);
23423     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23424       Other = LHS;
23425     }
23426
23427     if (Other.getNode() && Other->getNumOperands() == 2 &&
23428         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23429       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23430       SDValue CondRHS = Cond->getOperand(1);
23431
23432       // Look for a general sub with unsigned saturation first.
23433       // x >= y ? x-y : 0 --> subus x, y
23434       // x >  y ? x-y : 0 --> subus x, y
23435       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23436           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23437         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23438
23439       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23440         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23441           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23442             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23443               // If the RHS is a constant we have to reverse the const
23444               // canonicalization.
23445               // x > C-1 ? x+-C : 0 --> subus x, C
23446               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23447                   CondRHSConst->getAPIntValue() ==
23448                       (-OpRHSConst->getAPIntValue() - 1))
23449                 return DAG.getNode(
23450                     X86ISD::SUBUS, DL, VT, OpLHS,
23451                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23452
23453           // Another special case: If C was a sign bit, the sub has been
23454           // canonicalized into a xor.
23455           // FIXME: Would it be better to use computeKnownBits to determine
23456           //        whether it's safe to decanonicalize the xor?
23457           // x s< 0 ? x^C : 0 --> subus x, C
23458           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23459               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23460               OpRHSConst->getAPIntValue().isSignBit())
23461             // Note that we have to rebuild the RHS constant here to ensure we
23462             // don't rely on particular values of undef lanes.
23463             return DAG.getNode(
23464                 X86ISD::SUBUS, DL, VT, OpLHS,
23465                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23466         }
23467     }
23468   }
23469
23470   // Simplify vector selection if condition value type matches vselect
23471   // operand type
23472   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23473     assert(Cond.getValueType().isVector() &&
23474            "vector select expects a vector selector!");
23475
23476     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23477     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23478
23479     // Try invert the condition if true value is not all 1s and false value
23480     // is not all 0s.
23481     if (!TValIsAllOnes && !FValIsAllZeros &&
23482         // Check if the selector will be produced by CMPP*/PCMP*
23483         Cond.getOpcode() == ISD::SETCC &&
23484         // Check if SETCC has already been promoted
23485         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23486             CondVT) {
23487       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23488       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23489
23490       if (TValIsAllZeros || FValIsAllOnes) {
23491         SDValue CC = Cond.getOperand(2);
23492         ISD::CondCode NewCC =
23493           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23494                                Cond.getOperand(0).getValueType().isInteger());
23495         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23496         std::swap(LHS, RHS);
23497         TValIsAllOnes = FValIsAllOnes;
23498         FValIsAllZeros = TValIsAllZeros;
23499       }
23500     }
23501
23502     if (TValIsAllOnes || FValIsAllZeros) {
23503       SDValue Ret;
23504
23505       if (TValIsAllOnes && FValIsAllZeros)
23506         Ret = Cond;
23507       else if (TValIsAllOnes)
23508         Ret =
23509             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23510       else if (FValIsAllZeros)
23511         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23512                           DAG.getBitcast(CondVT, LHS));
23513
23514       return DAG.getBitcast(VT, Ret);
23515     }
23516   }
23517
23518   // We should generate an X86ISD::BLENDI from a vselect if its argument
23519   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23520   // constants. This specific pattern gets generated when we split a
23521   // selector for a 512 bit vector in a machine without AVX512 (but with
23522   // 256-bit vectors), during legalization:
23523   //
23524   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23525   //
23526   // Iff we find this pattern and the build_vectors are built from
23527   // constants, we translate the vselect into a shuffle_vector that we
23528   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23529   if ((N->getOpcode() == ISD::VSELECT ||
23530        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23531       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23532     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23533     if (Shuffle.getNode())
23534       return Shuffle;
23535   }
23536
23537   // If this is a *dynamic* select (non-constant condition) and we can match
23538   // this node with one of the variable blend instructions, restructure the
23539   // condition so that the blends can use the high bit of each element and use
23540   // SimplifyDemandedBits to simplify the condition operand.
23541   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23542       !DCI.isBeforeLegalize() &&
23543       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23544     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23545
23546     // Don't optimize vector selects that map to mask-registers.
23547     if (BitWidth == 1)
23548       return SDValue();
23549
23550     // We can only handle the cases where VSELECT is directly legal on the
23551     // subtarget. We custom lower VSELECT nodes with constant conditions and
23552     // this makes it hard to see whether a dynamic VSELECT will correctly
23553     // lower, so we both check the operation's status and explicitly handle the
23554     // cases where a *dynamic* blend will fail even though a constant-condition
23555     // blend could be custom lowered.
23556     // FIXME: We should find a better way to handle this class of problems.
23557     // Potentially, we should combine constant-condition vselect nodes
23558     // pre-legalization into shuffles and not mark as many types as custom
23559     // lowered.
23560     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23561       return SDValue();
23562     // FIXME: We don't support i16-element blends currently. We could and
23563     // should support them by making *all* the bits in the condition be set
23564     // rather than just the high bit and using an i8-element blend.
23565     if (VT.getScalarType() == MVT::i16)
23566       return SDValue();
23567     // Dynamic blending was only available from SSE4.1 onward.
23568     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23569       return SDValue();
23570     // Byte blends are only available in AVX2
23571     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23572         !Subtarget->hasAVX2())
23573       return SDValue();
23574
23575     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23576     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23577
23578     APInt KnownZero, KnownOne;
23579     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23580                                           DCI.isBeforeLegalizeOps());
23581     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23582         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23583                                  TLO)) {
23584       // If we changed the computation somewhere in the DAG, this change
23585       // will affect all users of Cond.
23586       // Make sure it is fine and update all the nodes so that we do not
23587       // use the generic VSELECT anymore. Otherwise, we may perform
23588       // wrong optimizations as we messed up with the actual expectation
23589       // for the vector boolean values.
23590       if (Cond != TLO.Old) {
23591         // Check all uses of that condition operand to check whether it will be
23592         // consumed by non-BLEND instructions, which may depend on all bits are
23593         // set properly.
23594         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23595              I != E; ++I)
23596           if (I->getOpcode() != ISD::VSELECT)
23597             // TODO: Add other opcodes eventually lowered into BLEND.
23598             return SDValue();
23599
23600         // Update all the users of the condition, before committing the change,
23601         // so that the VSELECT optimizations that expect the correct vector
23602         // boolean value will not be triggered.
23603         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23604              I != E; ++I)
23605           DAG.ReplaceAllUsesOfValueWith(
23606               SDValue(*I, 0),
23607               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23608                           Cond, I->getOperand(1), I->getOperand(2)));
23609         DCI.CommitTargetLoweringOpt(TLO);
23610         return SDValue();
23611       }
23612       // At this point, only Cond is changed. Change the condition
23613       // just for N to keep the opportunity to optimize all other
23614       // users their own way.
23615       DAG.ReplaceAllUsesOfValueWith(
23616           SDValue(N, 0),
23617           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23618                       TLO.New, N->getOperand(1), N->getOperand(2)));
23619       return SDValue();
23620     }
23621   }
23622
23623   return SDValue();
23624 }
23625
23626 // Check whether a boolean test is testing a boolean value generated by
23627 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23628 // code.
23629 //
23630 // Simplify the following patterns:
23631 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23632 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23633 // to (Op EFLAGS Cond)
23634 //
23635 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23636 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23637 // to (Op EFLAGS !Cond)
23638 //
23639 // where Op could be BRCOND or CMOV.
23640 //
23641 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23642   // Quit if not CMP and SUB with its value result used.
23643   if (Cmp.getOpcode() != X86ISD::CMP &&
23644       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23645       return SDValue();
23646
23647   // Quit if not used as a boolean value.
23648   if (CC != X86::COND_E && CC != X86::COND_NE)
23649     return SDValue();
23650
23651   // Check CMP operands. One of them should be 0 or 1 and the other should be
23652   // an SetCC or extended from it.
23653   SDValue Op1 = Cmp.getOperand(0);
23654   SDValue Op2 = Cmp.getOperand(1);
23655
23656   SDValue SetCC;
23657   const ConstantSDNode* C = nullptr;
23658   bool needOppositeCond = (CC == X86::COND_E);
23659   bool checkAgainstTrue = false; // Is it a comparison against 1?
23660
23661   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23662     SetCC = Op2;
23663   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23664     SetCC = Op1;
23665   else // Quit if all operands are not constants.
23666     return SDValue();
23667
23668   if (C->getZExtValue() == 1) {
23669     needOppositeCond = !needOppositeCond;
23670     checkAgainstTrue = true;
23671   } else if (C->getZExtValue() != 0)
23672     // Quit if the constant is neither 0 or 1.
23673     return SDValue();
23674
23675   bool truncatedToBoolWithAnd = false;
23676   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23677   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23678          SetCC.getOpcode() == ISD::TRUNCATE ||
23679          SetCC.getOpcode() == ISD::AND) {
23680     if (SetCC.getOpcode() == ISD::AND) {
23681       int OpIdx = -1;
23682       ConstantSDNode *CS;
23683       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23684           CS->getZExtValue() == 1)
23685         OpIdx = 1;
23686       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23687           CS->getZExtValue() == 1)
23688         OpIdx = 0;
23689       if (OpIdx == -1)
23690         break;
23691       SetCC = SetCC.getOperand(OpIdx);
23692       truncatedToBoolWithAnd = true;
23693     } else
23694       SetCC = SetCC.getOperand(0);
23695   }
23696
23697   switch (SetCC.getOpcode()) {
23698   case X86ISD::SETCC_CARRY:
23699     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23700     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23701     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23702     // truncated to i1 using 'and'.
23703     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23704       break;
23705     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23706            "Invalid use of SETCC_CARRY!");
23707     // FALL THROUGH
23708   case X86ISD::SETCC:
23709     // Set the condition code or opposite one if necessary.
23710     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23711     if (needOppositeCond)
23712       CC = X86::GetOppositeBranchCondition(CC);
23713     return SetCC.getOperand(1);
23714   case X86ISD::CMOV: {
23715     // Check whether false/true value has canonical one, i.e. 0 or 1.
23716     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23717     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23718     // Quit if true value is not a constant.
23719     if (!TVal)
23720       return SDValue();
23721     // Quit if false value is not a constant.
23722     if (!FVal) {
23723       SDValue Op = SetCC.getOperand(0);
23724       // Skip 'zext' or 'trunc' node.
23725       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23726           Op.getOpcode() == ISD::TRUNCATE)
23727         Op = Op.getOperand(0);
23728       // A special case for rdrand/rdseed, where 0 is set if false cond is
23729       // found.
23730       if ((Op.getOpcode() != X86ISD::RDRAND &&
23731            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23732         return SDValue();
23733     }
23734     // Quit if false value is not the constant 0 or 1.
23735     bool FValIsFalse = true;
23736     if (FVal && FVal->getZExtValue() != 0) {
23737       if (FVal->getZExtValue() != 1)
23738         return SDValue();
23739       // If FVal is 1, opposite cond is needed.
23740       needOppositeCond = !needOppositeCond;
23741       FValIsFalse = false;
23742     }
23743     // Quit if TVal is not the constant opposite of FVal.
23744     if (FValIsFalse && TVal->getZExtValue() != 1)
23745       return SDValue();
23746     if (!FValIsFalse && TVal->getZExtValue() != 0)
23747       return SDValue();
23748     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23749     if (needOppositeCond)
23750       CC = X86::GetOppositeBranchCondition(CC);
23751     return SetCC.getOperand(3);
23752   }
23753   }
23754
23755   return SDValue();
23756 }
23757
23758 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23759 /// Match:
23760 ///   (X86or (X86setcc) (X86setcc))
23761 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23762 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23763                                            X86::CondCode &CC1, SDValue &Flags,
23764                                            bool &isAnd) {
23765   if (Cond->getOpcode() == X86ISD::CMP) {
23766     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23767     if (!CondOp1C || !CondOp1C->isNullValue())
23768       return false;
23769
23770     Cond = Cond->getOperand(0);
23771   }
23772
23773   isAnd = false;
23774
23775   SDValue SetCC0, SetCC1;
23776   switch (Cond->getOpcode()) {
23777   default: return false;
23778   case ISD::AND:
23779   case X86ISD::AND:
23780     isAnd = true;
23781     // fallthru
23782   case ISD::OR:
23783   case X86ISD::OR:
23784     SetCC0 = Cond->getOperand(0);
23785     SetCC1 = Cond->getOperand(1);
23786     break;
23787   };
23788
23789   // Make sure we have SETCC nodes, using the same flags value.
23790   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23791       SetCC1.getOpcode() != X86ISD::SETCC ||
23792       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23793     return false;
23794
23795   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23796   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23797   Flags = SetCC0->getOperand(1);
23798   return true;
23799 }
23800
23801 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23802 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23803                                   TargetLowering::DAGCombinerInfo &DCI,
23804                                   const X86Subtarget *Subtarget) {
23805   SDLoc DL(N);
23806
23807   // If the flag operand isn't dead, don't touch this CMOV.
23808   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23809     return SDValue();
23810
23811   SDValue FalseOp = N->getOperand(0);
23812   SDValue TrueOp = N->getOperand(1);
23813   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23814   SDValue Cond = N->getOperand(3);
23815
23816   if (CC == X86::COND_E || CC == X86::COND_NE) {
23817     switch (Cond.getOpcode()) {
23818     default: break;
23819     case X86ISD::BSR:
23820     case X86ISD::BSF:
23821       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23822       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23823         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23824     }
23825   }
23826
23827   SDValue Flags;
23828
23829   Flags = checkBoolTestSetCCCombine(Cond, CC);
23830   if (Flags.getNode() &&
23831       // Extra check as FCMOV only supports a subset of X86 cond.
23832       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23833     SDValue Ops[] = { FalseOp, TrueOp,
23834                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23835     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23836   }
23837
23838   // If this is a select between two integer constants, try to do some
23839   // optimizations.  Note that the operands are ordered the opposite of SELECT
23840   // operands.
23841   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23842     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23843       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23844       // larger than FalseC (the false value).
23845       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23846         CC = X86::GetOppositeBranchCondition(CC);
23847         std::swap(TrueC, FalseC);
23848         std::swap(TrueOp, FalseOp);
23849       }
23850
23851       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23852       // This is efficient for any integer data type (including i8/i16) and
23853       // shift amount.
23854       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23855         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23856                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23857
23858         // Zero extend the condition if needed.
23859         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23860
23861         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23862         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23863                            DAG.getConstant(ShAmt, DL, MVT::i8));
23864         if (N->getNumValues() == 2)  // Dead flag value?
23865           return DCI.CombineTo(N, Cond, SDValue());
23866         return Cond;
23867       }
23868
23869       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23870       // for any integer data type, including i8/i16.
23871       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23872         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23873                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23874
23875         // Zero extend the condition if needed.
23876         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23877                            FalseC->getValueType(0), Cond);
23878         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23879                            SDValue(FalseC, 0));
23880
23881         if (N->getNumValues() == 2)  // Dead flag value?
23882           return DCI.CombineTo(N, Cond, SDValue());
23883         return Cond;
23884       }
23885
23886       // Optimize cases that will turn into an LEA instruction.  This requires
23887       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23888       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23889         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23890         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23891
23892         bool isFastMultiplier = false;
23893         if (Diff < 10) {
23894           switch ((unsigned char)Diff) {
23895           default: break;
23896           case 1:  // result = add base, cond
23897           case 2:  // result = lea base(    , cond*2)
23898           case 3:  // result = lea base(cond, cond*2)
23899           case 4:  // result = lea base(    , cond*4)
23900           case 5:  // result = lea base(cond, cond*4)
23901           case 8:  // result = lea base(    , cond*8)
23902           case 9:  // result = lea base(cond, cond*8)
23903             isFastMultiplier = true;
23904             break;
23905           }
23906         }
23907
23908         if (isFastMultiplier) {
23909           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23910           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23911                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23912           // Zero extend the condition if needed.
23913           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23914                              Cond);
23915           // Scale the condition by the difference.
23916           if (Diff != 1)
23917             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23918                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23919
23920           // Add the base if non-zero.
23921           if (FalseC->getAPIntValue() != 0)
23922             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23923                                SDValue(FalseC, 0));
23924           if (N->getNumValues() == 2)  // Dead flag value?
23925             return DCI.CombineTo(N, Cond, SDValue());
23926           return Cond;
23927         }
23928       }
23929     }
23930   }
23931
23932   // Handle these cases:
23933   //   (select (x != c), e, c) -> select (x != c), e, x),
23934   //   (select (x == c), c, e) -> select (x == c), x, e)
23935   // where the c is an integer constant, and the "select" is the combination
23936   // of CMOV and CMP.
23937   //
23938   // The rationale for this change is that the conditional-move from a constant
23939   // needs two instructions, however, conditional-move from a register needs
23940   // only one instruction.
23941   //
23942   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23943   //  some instruction-combining opportunities. This opt needs to be
23944   //  postponed as late as possible.
23945   //
23946   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23947     // the DCI.xxxx conditions are provided to postpone the optimization as
23948     // late as possible.
23949
23950     ConstantSDNode *CmpAgainst = nullptr;
23951     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23952         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23953         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23954
23955       if (CC == X86::COND_NE &&
23956           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23957         CC = X86::GetOppositeBranchCondition(CC);
23958         std::swap(TrueOp, FalseOp);
23959       }
23960
23961       if (CC == X86::COND_E &&
23962           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23963         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23964                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23965         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23966       }
23967     }
23968   }
23969
23970   // Fold and/or of setcc's to double CMOV:
23971   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23972   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23973   //
23974   // This combine lets us generate:
23975   //   cmovcc1 (jcc1 if we don't have CMOV)
23976   //   cmovcc2 (same)
23977   // instead of:
23978   //   setcc1
23979   //   setcc2
23980   //   and/or
23981   //   cmovne (jne if we don't have CMOV)
23982   // When we can't use the CMOV instruction, it might increase branch
23983   // mispredicts.
23984   // When we can use CMOV, or when there is no mispredict, this improves
23985   // throughput and reduces register pressure.
23986   //
23987   if (CC == X86::COND_NE) {
23988     SDValue Flags;
23989     X86::CondCode CC0, CC1;
23990     bool isAndSetCC;
23991     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23992       if (isAndSetCC) {
23993         std::swap(FalseOp, TrueOp);
23994         CC0 = X86::GetOppositeBranchCondition(CC0);
23995         CC1 = X86::GetOppositeBranchCondition(CC1);
23996       }
23997
23998       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23999         Flags};
24000       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24001       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24002       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24003       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24004       return CMOV;
24005     }
24006   }
24007
24008   return SDValue();
24009 }
24010
24011 /// PerformMulCombine - Optimize a single multiply with constant into two
24012 /// in order to implement it with two cheaper instructions, e.g.
24013 /// LEA + SHL, LEA + LEA.
24014 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24015                                  TargetLowering::DAGCombinerInfo &DCI) {
24016   // An imul is usually smaller than the alternative sequence.
24017   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24018     return SDValue();
24019
24020   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24021     return SDValue();
24022
24023   EVT VT = N->getValueType(0);
24024   if (VT != MVT::i64 && VT != MVT::i32)
24025     return SDValue();
24026
24027   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24028   if (!C)
24029     return SDValue();
24030   uint64_t MulAmt = C->getZExtValue();
24031   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24032     return SDValue();
24033
24034   uint64_t MulAmt1 = 0;
24035   uint64_t MulAmt2 = 0;
24036   if ((MulAmt % 9) == 0) {
24037     MulAmt1 = 9;
24038     MulAmt2 = MulAmt / 9;
24039   } else if ((MulAmt % 5) == 0) {
24040     MulAmt1 = 5;
24041     MulAmt2 = MulAmt / 5;
24042   } else if ((MulAmt % 3) == 0) {
24043     MulAmt1 = 3;
24044     MulAmt2 = MulAmt / 3;
24045   }
24046   if (MulAmt2 &&
24047       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24048     SDLoc DL(N);
24049
24050     if (isPowerOf2_64(MulAmt2) &&
24051         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24052       // If second multiplifer is pow2, issue it first. We want the multiply by
24053       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24054       // is an add.
24055       std::swap(MulAmt1, MulAmt2);
24056
24057     SDValue NewMul;
24058     if (isPowerOf2_64(MulAmt1))
24059       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24060                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24061     else
24062       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24063                            DAG.getConstant(MulAmt1, DL, VT));
24064
24065     if (isPowerOf2_64(MulAmt2))
24066       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24067                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24068     else
24069       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24070                            DAG.getConstant(MulAmt2, DL, VT));
24071
24072     // Do not add new nodes to DAG combiner worklist.
24073     DCI.CombineTo(N, NewMul, false);
24074   }
24075   return SDValue();
24076 }
24077
24078 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24079   SDValue N0 = N->getOperand(0);
24080   SDValue N1 = N->getOperand(1);
24081   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24082   EVT VT = N0.getValueType();
24083
24084   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24085   // since the result of setcc_c is all zero's or all ones.
24086   if (VT.isInteger() && !VT.isVector() &&
24087       N1C && N0.getOpcode() == ISD::AND &&
24088       N0.getOperand(1).getOpcode() == ISD::Constant) {
24089     SDValue N00 = N0.getOperand(0);
24090     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24091     APInt ShAmt = N1C->getAPIntValue();
24092     Mask = Mask.shl(ShAmt);
24093     bool MaskOK = false;
24094     // We can handle cases concerning bit-widening nodes containing setcc_c if
24095     // we carefully interrogate the mask to make sure we are semantics
24096     // preserving.
24097     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24098     // of the underlying setcc_c operation if the setcc_c was zero extended.
24099     // Consider the following example:
24100     //   zext(setcc_c)                 -> i32 0x0000FFFF
24101     //   c1                            -> i32 0x0000FFFF
24102     //   c2                            -> i32 0x00000001
24103     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24104     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24105     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24106       MaskOK = true;
24107     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24108                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24109       MaskOK = true;
24110     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24111                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24112                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24113       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24114     }
24115     if (MaskOK && Mask != 0) {
24116       SDLoc DL(N);
24117       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24118     }
24119   }
24120
24121   // Hardware support for vector shifts is sparse which makes us scalarize the
24122   // vector operations in many cases. Also, on sandybridge ADD is faster than
24123   // shl.
24124   // (shl V, 1) -> add V,V
24125   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24126     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24127       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24128       // We shift all of the values by one. In many cases we do not have
24129       // hardware support for this operation. This is better expressed as an ADD
24130       // of two values.
24131       if (N1SplatC->getAPIntValue() == 1)
24132         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24133     }
24134
24135   return SDValue();
24136 }
24137
24138 /// \brief Returns a vector of 0s if the node in input is a vector logical
24139 /// shift by a constant amount which is known to be bigger than or equal
24140 /// to the vector element size in bits.
24141 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24142                                       const X86Subtarget *Subtarget) {
24143   EVT VT = N->getValueType(0);
24144
24145   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24146       (!Subtarget->hasInt256() ||
24147        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24148     return SDValue();
24149
24150   SDValue Amt = N->getOperand(1);
24151   SDLoc DL(N);
24152   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24153     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24154       APInt ShiftAmt = AmtSplat->getAPIntValue();
24155       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24156
24157       // SSE2/AVX2 logical shifts always return a vector of 0s
24158       // if the shift amount is bigger than or equal to
24159       // the element size. The constant shift amount will be
24160       // encoded as a 8-bit immediate.
24161       if (ShiftAmt.trunc(8).uge(MaxAmount))
24162         return getZeroVector(VT, Subtarget, DAG, DL);
24163     }
24164
24165   return SDValue();
24166 }
24167
24168 /// PerformShiftCombine - Combine shifts.
24169 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24170                                    TargetLowering::DAGCombinerInfo &DCI,
24171                                    const X86Subtarget *Subtarget) {
24172   if (N->getOpcode() == ISD::SHL)
24173     if (SDValue V = PerformSHLCombine(N, DAG))
24174       return V;
24175
24176   // Try to fold this logical shift into a zero vector.
24177   if (N->getOpcode() != ISD::SRA)
24178     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24179       return V;
24180
24181   return SDValue();
24182 }
24183
24184 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24185 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24186 // and friends.  Likewise for OR -> CMPNEQSS.
24187 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24188                             TargetLowering::DAGCombinerInfo &DCI,
24189                             const X86Subtarget *Subtarget) {
24190   unsigned opcode;
24191
24192   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24193   // we're requiring SSE2 for both.
24194   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24195     SDValue N0 = N->getOperand(0);
24196     SDValue N1 = N->getOperand(1);
24197     SDValue CMP0 = N0->getOperand(1);
24198     SDValue CMP1 = N1->getOperand(1);
24199     SDLoc DL(N);
24200
24201     // The SETCCs should both refer to the same CMP.
24202     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24203       return SDValue();
24204
24205     SDValue CMP00 = CMP0->getOperand(0);
24206     SDValue CMP01 = CMP0->getOperand(1);
24207     EVT     VT    = CMP00.getValueType();
24208
24209     if (VT == MVT::f32 || VT == MVT::f64) {
24210       bool ExpectingFlags = false;
24211       // Check for any users that want flags:
24212       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24213            !ExpectingFlags && UI != UE; ++UI)
24214         switch (UI->getOpcode()) {
24215         default:
24216         case ISD::BR_CC:
24217         case ISD::BRCOND:
24218         case ISD::SELECT:
24219           ExpectingFlags = true;
24220           break;
24221         case ISD::CopyToReg:
24222         case ISD::SIGN_EXTEND:
24223         case ISD::ZERO_EXTEND:
24224         case ISD::ANY_EXTEND:
24225           break;
24226         }
24227
24228       if (!ExpectingFlags) {
24229         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24230         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24231
24232         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24233           X86::CondCode tmp = cc0;
24234           cc0 = cc1;
24235           cc1 = tmp;
24236         }
24237
24238         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24239             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24240           // FIXME: need symbolic constants for these magic numbers.
24241           // See X86ATTInstPrinter.cpp:printSSECC().
24242           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24243           if (Subtarget->hasAVX512()) {
24244             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24245                                          CMP01,
24246                                          DAG.getConstant(x86cc, DL, MVT::i8));
24247             if (N->getValueType(0) != MVT::i1)
24248               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24249                                  FSetCC);
24250             return FSetCC;
24251           }
24252           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24253                                               CMP00.getValueType(), CMP00, CMP01,
24254                                               DAG.getConstant(x86cc, DL,
24255                                                               MVT::i8));
24256
24257           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24258           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24259
24260           if (is64BitFP && !Subtarget->is64Bit()) {
24261             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24262             // 64-bit integer, since that's not a legal type. Since
24263             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24264             // bits, but can do this little dance to extract the lowest 32 bits
24265             // and work with those going forward.
24266             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24267                                            OnesOrZeroesF);
24268             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24269             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24270                                         Vector32, DAG.getIntPtrConstant(0, DL));
24271             IntVT = MVT::i32;
24272           }
24273
24274           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24275           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24276                                       DAG.getConstant(1, DL, IntVT));
24277           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24278                                               ANDed);
24279           return OneBitOfTruth;
24280         }
24281       }
24282     }
24283   }
24284   return SDValue();
24285 }
24286
24287 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24288 /// so it can be folded inside ANDNP.
24289 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24290   EVT VT = N->getValueType(0);
24291
24292   // Match direct AllOnes for 128 and 256-bit vectors
24293   if (ISD::isBuildVectorAllOnes(N))
24294     return true;
24295
24296   // Look through a bit convert.
24297   if (N->getOpcode() == ISD::BITCAST)
24298     N = N->getOperand(0).getNode();
24299
24300   // Sometimes the operand may come from a insert_subvector building a 256-bit
24301   // allones vector
24302   if (VT.is256BitVector() &&
24303       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24304     SDValue V1 = N->getOperand(0);
24305     SDValue V2 = N->getOperand(1);
24306
24307     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24308         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24309         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24310         ISD::isBuildVectorAllOnes(V2.getNode()))
24311       return true;
24312   }
24313
24314   return false;
24315 }
24316
24317 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24318 // register. In most cases we actually compare or select YMM-sized registers
24319 // and mixing the two types creates horrible code. This method optimizes
24320 // some of the transition sequences.
24321 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24322                                  TargetLowering::DAGCombinerInfo &DCI,
24323                                  const X86Subtarget *Subtarget) {
24324   EVT VT = N->getValueType(0);
24325   if (!VT.is256BitVector())
24326     return SDValue();
24327
24328   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24329           N->getOpcode() == ISD::ZERO_EXTEND ||
24330           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24331
24332   SDValue Narrow = N->getOperand(0);
24333   EVT NarrowVT = Narrow->getValueType(0);
24334   if (!NarrowVT.is128BitVector())
24335     return SDValue();
24336
24337   if (Narrow->getOpcode() != ISD::XOR &&
24338       Narrow->getOpcode() != ISD::AND &&
24339       Narrow->getOpcode() != ISD::OR)
24340     return SDValue();
24341
24342   SDValue N0  = Narrow->getOperand(0);
24343   SDValue N1  = Narrow->getOperand(1);
24344   SDLoc DL(Narrow);
24345
24346   // The Left side has to be a trunc.
24347   if (N0.getOpcode() != ISD::TRUNCATE)
24348     return SDValue();
24349
24350   // The type of the truncated inputs.
24351   EVT WideVT = N0->getOperand(0)->getValueType(0);
24352   if (WideVT != VT)
24353     return SDValue();
24354
24355   // The right side has to be a 'trunc' or a constant vector.
24356   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24357   ConstantSDNode *RHSConstSplat = nullptr;
24358   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24359     RHSConstSplat = RHSBV->getConstantSplatNode();
24360   if (!RHSTrunc && !RHSConstSplat)
24361     return SDValue();
24362
24363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24364
24365   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24366     return SDValue();
24367
24368   // Set N0 and N1 to hold the inputs to the new wide operation.
24369   N0 = N0->getOperand(0);
24370   if (RHSConstSplat) {
24371     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24372                      SDValue(RHSConstSplat, 0));
24373     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24374     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24375   } else if (RHSTrunc) {
24376     N1 = N1->getOperand(0);
24377   }
24378
24379   // Generate the wide operation.
24380   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24381   unsigned Opcode = N->getOpcode();
24382   switch (Opcode) {
24383   case ISD::ANY_EXTEND:
24384     return Op;
24385   case ISD::ZERO_EXTEND: {
24386     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24387     APInt Mask = APInt::getAllOnesValue(InBits);
24388     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24389     return DAG.getNode(ISD::AND, DL, VT,
24390                        Op, DAG.getConstant(Mask, DL, VT));
24391   }
24392   case ISD::SIGN_EXTEND:
24393     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24394                        Op, DAG.getValueType(NarrowVT));
24395   default:
24396     llvm_unreachable("Unexpected opcode");
24397   }
24398 }
24399
24400 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24401                                  TargetLowering::DAGCombinerInfo &DCI,
24402                                  const X86Subtarget *Subtarget) {
24403   SDValue N0 = N->getOperand(0);
24404   SDValue N1 = N->getOperand(1);
24405   SDLoc DL(N);
24406
24407   // A vector zext_in_reg may be represented as a shuffle,
24408   // feeding into a bitcast (this represents anyext) feeding into
24409   // an and with a mask.
24410   // We'd like to try to combine that into a shuffle with zero
24411   // plus a bitcast, removing the and.
24412   if (N0.getOpcode() != ISD::BITCAST ||
24413       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24414     return SDValue();
24415
24416   // The other side of the AND should be a splat of 2^C, where C
24417   // is the number of bits in the source type.
24418   if (N1.getOpcode() == ISD::BITCAST)
24419     N1 = N1.getOperand(0);
24420   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24421     return SDValue();
24422   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24423
24424   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24425   EVT SrcType = Shuffle->getValueType(0);
24426
24427   // We expect a single-source shuffle
24428   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24429     return SDValue();
24430
24431   unsigned SrcSize = SrcType.getScalarSizeInBits();
24432
24433   APInt SplatValue, SplatUndef;
24434   unsigned SplatBitSize;
24435   bool HasAnyUndefs;
24436   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24437                                 SplatBitSize, HasAnyUndefs))
24438     return SDValue();
24439
24440   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24441   // Make sure the splat matches the mask we expect
24442   if (SplatBitSize > ResSize ||
24443       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24444     return SDValue();
24445
24446   // Make sure the input and output size make sense
24447   if (SrcSize >= ResSize || ResSize % SrcSize)
24448     return SDValue();
24449
24450   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24451   // The number of u's between each two values depends on the ratio between
24452   // the source and dest type.
24453   unsigned ZextRatio = ResSize / SrcSize;
24454   bool IsZext = true;
24455   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24456     if (i % ZextRatio) {
24457       if (Shuffle->getMaskElt(i) > 0) {
24458         // Expected undef
24459         IsZext = false;
24460         break;
24461       }
24462     } else {
24463       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24464         // Expected element number
24465         IsZext = false;
24466         break;
24467       }
24468     }
24469   }
24470
24471   if (!IsZext)
24472     return SDValue();
24473
24474   // Ok, perform the transformation - replace the shuffle with
24475   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24476   // (instead of undef) where the k elements come from the zero vector.
24477   SmallVector<int, 8> Mask;
24478   unsigned NumElems = SrcType.getVectorNumElements();
24479   for (unsigned i = 0; i < NumElems; ++i)
24480     if (i % ZextRatio)
24481       Mask.push_back(NumElems);
24482     else
24483       Mask.push_back(i / ZextRatio);
24484
24485   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24486     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24487   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24488 }
24489
24490 /// If both input operands of a logic op are being cast from floating point
24491 /// types, try to convert this into a floating point logic node to avoid
24492 /// unnecessary moves from SSE to integer registers.
24493 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24494                                         const X86Subtarget *Subtarget) {
24495   unsigned FPOpcode = ISD::DELETED_NODE;
24496   if (N->getOpcode() == ISD::AND)
24497     FPOpcode = X86ISD::FAND;
24498   else if (N->getOpcode() == ISD::OR)
24499     FPOpcode = X86ISD::FOR;
24500   else if (N->getOpcode() == ISD::XOR)
24501     FPOpcode = X86ISD::FXOR;
24502
24503   assert(FPOpcode != ISD::DELETED_NODE &&
24504          "Unexpected input node for FP logic conversion");
24505
24506   EVT VT = N->getValueType(0);
24507   SDValue N0 = N->getOperand(0);
24508   SDValue N1 = N->getOperand(1);
24509   SDLoc DL(N);
24510   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24511       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24512        (Subtarget->hasSSE2() && VT == MVT::i64))) {
24513     SDValue N00 = N0.getOperand(0);
24514     SDValue N10 = N1.getOperand(0);
24515     EVT N00Type = N00.getValueType();
24516     EVT N10Type = N10.getValueType();
24517     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24518       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24519       return DAG.getBitcast(VT, FPLogic);
24520     }
24521   }
24522   return SDValue();
24523 }
24524
24525 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24526                                  TargetLowering::DAGCombinerInfo &DCI,
24527                                  const X86Subtarget *Subtarget) {
24528   if (DCI.isBeforeLegalizeOps())
24529     return SDValue();
24530
24531   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24532     return Zext;
24533
24534   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24535     return R;
24536
24537   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24538     return FPLogic;
24539
24540   EVT VT = N->getValueType(0);
24541   SDValue N0 = N->getOperand(0);
24542   SDValue N1 = N->getOperand(1);
24543   SDLoc DL(N);
24544
24545   // Create BEXTR instructions
24546   // BEXTR is ((X >> imm) & (2**size-1))
24547   if (VT == MVT::i32 || VT == MVT::i64) {
24548     // Check for BEXTR.
24549     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24550         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24551       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24552       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24553       if (MaskNode && ShiftNode) {
24554         uint64_t Mask = MaskNode->getZExtValue();
24555         uint64_t Shift = ShiftNode->getZExtValue();
24556         if (isMask_64(Mask)) {
24557           uint64_t MaskSize = countPopulation(Mask);
24558           if (Shift + MaskSize <= VT.getSizeInBits())
24559             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24560                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24561                                                VT));
24562         }
24563       }
24564     } // BEXTR
24565
24566     return SDValue();
24567   }
24568
24569   // Want to form ANDNP nodes:
24570   // 1) In the hopes of then easily combining them with OR and AND nodes
24571   //    to form PBLEND/PSIGN.
24572   // 2) To match ANDN packed intrinsics
24573   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24574     return SDValue();
24575
24576   // Check LHS for vnot
24577   if (N0.getOpcode() == ISD::XOR &&
24578       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24579       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24580     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24581
24582   // Check RHS for vnot
24583   if (N1.getOpcode() == ISD::XOR &&
24584       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24585       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24586     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24587
24588   return SDValue();
24589 }
24590
24591 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24592                                 TargetLowering::DAGCombinerInfo &DCI,
24593                                 const X86Subtarget *Subtarget) {
24594   if (DCI.isBeforeLegalizeOps())
24595     return SDValue();
24596
24597   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24598     return R;
24599
24600   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24601     return FPLogic;
24602
24603   SDValue N0 = N->getOperand(0);
24604   SDValue N1 = N->getOperand(1);
24605   EVT VT = N->getValueType(0);
24606
24607   // look for psign/blend
24608   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24609     if (!Subtarget->hasSSSE3() ||
24610         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24611       return SDValue();
24612
24613     // Canonicalize pandn to RHS
24614     if (N0.getOpcode() == X86ISD::ANDNP)
24615       std::swap(N0, N1);
24616     // or (and (m, y), (pandn m, x))
24617     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24618       SDValue Mask = N1.getOperand(0);
24619       SDValue X    = N1.getOperand(1);
24620       SDValue Y;
24621       if (N0.getOperand(0) == Mask)
24622         Y = N0.getOperand(1);
24623       if (N0.getOperand(1) == Mask)
24624         Y = N0.getOperand(0);
24625
24626       // Check to see if the mask appeared in both the AND and ANDNP and
24627       if (!Y.getNode())
24628         return SDValue();
24629
24630       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24631       // Look through mask bitcast.
24632       if (Mask.getOpcode() == ISD::BITCAST)
24633         Mask = Mask.getOperand(0);
24634       if (X.getOpcode() == ISD::BITCAST)
24635         X = X.getOperand(0);
24636       if (Y.getOpcode() == ISD::BITCAST)
24637         Y = Y.getOperand(0);
24638
24639       EVT MaskVT = Mask.getValueType();
24640
24641       // Validate that the Mask operand is a vector sra node.
24642       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24643       // there is no psrai.b
24644       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24645       unsigned SraAmt = ~0;
24646       if (Mask.getOpcode() == ISD::SRA) {
24647         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24648           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24649             SraAmt = AmtConst->getZExtValue();
24650       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24651         SDValue SraC = Mask.getOperand(1);
24652         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24653       }
24654       if ((SraAmt + 1) != EltBits)
24655         return SDValue();
24656
24657       SDLoc DL(N);
24658
24659       // Now we know we at least have a plendvb with the mask val.  See if
24660       // we can form a psignb/w/d.
24661       // psign = x.type == y.type == mask.type && y = sub(0, x);
24662       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24663           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24664           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24665         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24666                "Unsupported VT for PSIGN");
24667         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24668         return DAG.getBitcast(VT, Mask);
24669       }
24670       // PBLENDVB only available on SSE 4.1
24671       if (!Subtarget->hasSSE41())
24672         return SDValue();
24673
24674       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24675
24676       X = DAG.getBitcast(BlendVT, X);
24677       Y = DAG.getBitcast(BlendVT, Y);
24678       Mask = DAG.getBitcast(BlendVT, Mask);
24679       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24680       return DAG.getBitcast(VT, Mask);
24681     }
24682   }
24683
24684   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24685     return SDValue();
24686
24687   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24688   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24689
24690   // SHLD/SHRD instructions have lower register pressure, but on some
24691   // platforms they have higher latency than the equivalent
24692   // series of shifts/or that would otherwise be generated.
24693   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24694   // have higher latencies and we are not optimizing for size.
24695   if (!OptForSize && Subtarget->isSHLDSlow())
24696     return SDValue();
24697
24698   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24699     std::swap(N0, N1);
24700   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24701     return SDValue();
24702   if (!N0.hasOneUse() || !N1.hasOneUse())
24703     return SDValue();
24704
24705   SDValue ShAmt0 = N0.getOperand(1);
24706   if (ShAmt0.getValueType() != MVT::i8)
24707     return SDValue();
24708   SDValue ShAmt1 = N1.getOperand(1);
24709   if (ShAmt1.getValueType() != MVT::i8)
24710     return SDValue();
24711   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24712     ShAmt0 = ShAmt0.getOperand(0);
24713   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24714     ShAmt1 = ShAmt1.getOperand(0);
24715
24716   SDLoc DL(N);
24717   unsigned Opc = X86ISD::SHLD;
24718   SDValue Op0 = N0.getOperand(0);
24719   SDValue Op1 = N1.getOperand(0);
24720   if (ShAmt0.getOpcode() == ISD::SUB) {
24721     Opc = X86ISD::SHRD;
24722     std::swap(Op0, Op1);
24723     std::swap(ShAmt0, ShAmt1);
24724   }
24725
24726   unsigned Bits = VT.getSizeInBits();
24727   if (ShAmt1.getOpcode() == ISD::SUB) {
24728     SDValue Sum = ShAmt1.getOperand(0);
24729     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24730       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24731       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24732         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24733       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24734         return DAG.getNode(Opc, DL, VT,
24735                            Op0, Op1,
24736                            DAG.getNode(ISD::TRUNCATE, DL,
24737                                        MVT::i8, ShAmt0));
24738     }
24739   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24740     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24741     if (ShAmt0C &&
24742         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24743       return DAG.getNode(Opc, DL, VT,
24744                          N0.getOperand(0), N1.getOperand(0),
24745                          DAG.getNode(ISD::TRUNCATE, DL,
24746                                        MVT::i8, ShAmt0));
24747   }
24748
24749   return SDValue();
24750 }
24751
24752 // Generate NEG and CMOV for integer abs.
24753 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24754   EVT VT = N->getValueType(0);
24755
24756   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24757   // 8-bit integer abs to NEG and CMOV.
24758   if (VT.isInteger() && VT.getSizeInBits() == 8)
24759     return SDValue();
24760
24761   SDValue N0 = N->getOperand(0);
24762   SDValue N1 = N->getOperand(1);
24763   SDLoc DL(N);
24764
24765   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24766   // and change it to SUB and CMOV.
24767   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24768       N0.getOpcode() == ISD::ADD &&
24769       N0.getOperand(1) == N1 &&
24770       N1.getOpcode() == ISD::SRA &&
24771       N1.getOperand(0) == N0.getOperand(0))
24772     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24773       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24774         // Generate SUB & CMOV.
24775         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24776                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24777
24778         SDValue Ops[] = { N0.getOperand(0), Neg,
24779                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24780                           SDValue(Neg.getNode(), 1) };
24781         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24782       }
24783   return SDValue();
24784 }
24785
24786 // Try to turn tests against the signbit in the form of:
24787 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24788 // into:
24789 //   SETGT(X, -1)
24790 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24791   // This is only worth doing if the output type is i8.
24792   if (N->getValueType(0) != MVT::i8)
24793     return SDValue();
24794
24795   SDValue N0 = N->getOperand(0);
24796   SDValue N1 = N->getOperand(1);
24797
24798   // We should be performing an xor against a truncated shift.
24799   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24800     return SDValue();
24801
24802   // Make sure we are performing an xor against one.
24803   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24804     return SDValue();
24805
24806   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24807   SDValue Shift = N0.getOperand(0);
24808   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24809     return SDValue();
24810
24811   // Make sure we are truncating from one of i16, i32 or i64.
24812   EVT ShiftTy = Shift.getValueType();
24813   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24814     return SDValue();
24815
24816   // Make sure the shift amount extracts the sign bit.
24817   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24818       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24819     return SDValue();
24820
24821   // Create a greater-than comparison against -1.
24822   // N.B. Using SETGE against 0 works but we want a canonical looking
24823   // comparison, using SETGT matches up with what TranslateX86CC.
24824   SDLoc DL(N);
24825   SDValue ShiftOp = Shift.getOperand(0);
24826   EVT ShiftOpTy = ShiftOp.getValueType();
24827   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24828                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24829   return Cond;
24830 }
24831
24832 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24833                                  TargetLowering::DAGCombinerInfo &DCI,
24834                                  const X86Subtarget *Subtarget) {
24835   if (DCI.isBeforeLegalizeOps())
24836     return SDValue();
24837
24838   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24839     return RV;
24840
24841   if (Subtarget->hasCMov())
24842     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24843       return RV;
24844
24845   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24846     return FPLogic;
24847
24848   return SDValue();
24849 }
24850
24851 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24852 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24853                                   TargetLowering::DAGCombinerInfo &DCI,
24854                                   const X86Subtarget *Subtarget) {
24855   LoadSDNode *Ld = cast<LoadSDNode>(N);
24856   EVT RegVT = Ld->getValueType(0);
24857   EVT MemVT = Ld->getMemoryVT();
24858   SDLoc dl(Ld);
24859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24860
24861   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24862   // into two 16-byte operations.
24863   ISD::LoadExtType Ext = Ld->getExtensionType();
24864   bool Fast;
24865   unsigned AddressSpace = Ld->getAddressSpace();
24866   unsigned Alignment = Ld->getAlignment();
24867   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24868       Ext == ISD::NON_EXTLOAD &&
24869       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24870                              AddressSpace, Alignment, &Fast) && !Fast) {
24871     unsigned NumElems = RegVT.getVectorNumElements();
24872     if (NumElems < 2)
24873       return SDValue();
24874
24875     SDValue Ptr = Ld->getBasePtr();
24876     SDValue Increment =
24877         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24878
24879     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24880                                   NumElems/2);
24881     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24882                                 Ld->getPointerInfo(), Ld->isVolatile(),
24883                                 Ld->isNonTemporal(), Ld->isInvariant(),
24884                                 Alignment);
24885     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24886     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24887                                 Ld->getPointerInfo(), Ld->isVolatile(),
24888                                 Ld->isNonTemporal(), Ld->isInvariant(),
24889                                 std::min(16U, Alignment));
24890     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24891                              Load1.getValue(1),
24892                              Load2.getValue(1));
24893
24894     SDValue NewVec = DAG.getUNDEF(RegVT);
24895     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24896     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24897     return DCI.CombineTo(N, NewVec, TF, true);
24898   }
24899
24900   return SDValue();
24901 }
24902
24903 /// PerformMLOADCombine - Resolve extending loads
24904 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24905                                    TargetLowering::DAGCombinerInfo &DCI,
24906                                    const X86Subtarget *Subtarget) {
24907   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24908   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24909     return SDValue();
24910
24911   EVT VT = Mld->getValueType(0);
24912   unsigned NumElems = VT.getVectorNumElements();
24913   EVT LdVT = Mld->getMemoryVT();
24914   SDLoc dl(Mld);
24915
24916   assert(LdVT != VT && "Cannot extend to the same type");
24917   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24918   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24919   // From, To sizes and ElemCount must be pow of two
24920   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24921     "Unexpected size for extending masked load");
24922
24923   unsigned SizeRatio  = ToSz / FromSz;
24924   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24925
24926   // Create a type on which we perform the shuffle
24927   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24928           LdVT.getScalarType(), NumElems*SizeRatio);
24929   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24930
24931   // Convert Src0 value
24932   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24933   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24934     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24935     for (unsigned i = 0; i != NumElems; ++i)
24936       ShuffleVec[i] = i * SizeRatio;
24937
24938     // Can't shuffle using an illegal type.
24939     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
24940            "WideVecVT should be legal");
24941     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24942                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24943   }
24944   // Prepare the new mask
24945   SDValue NewMask;
24946   SDValue Mask = Mld->getMask();
24947   if (Mask.getValueType() == VT) {
24948     // Mask and original value have the same type
24949     NewMask = DAG.getBitcast(WideVecVT, Mask);
24950     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24951     for (unsigned i = 0; i != NumElems; ++i)
24952       ShuffleVec[i] = i * SizeRatio;
24953     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24954       ShuffleVec[i] = NumElems*SizeRatio;
24955     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24956                                    DAG.getConstant(0, dl, WideVecVT),
24957                                    &ShuffleVec[0]);
24958   }
24959   else {
24960     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24961     unsigned WidenNumElts = NumElems*SizeRatio;
24962     unsigned MaskNumElts = VT.getVectorNumElements();
24963     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24964                                      WidenNumElts);
24965
24966     unsigned NumConcat = WidenNumElts / MaskNumElts;
24967     SmallVector<SDValue, 16> Ops(NumConcat);
24968     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24969     Ops[0] = Mask;
24970     for (unsigned i = 1; i != NumConcat; ++i)
24971       Ops[i] = ZeroVal;
24972
24973     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24974   }
24975
24976   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24977                                      Mld->getBasePtr(), NewMask, WideSrc0,
24978                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24979                                      ISD::NON_EXTLOAD);
24980   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24981   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24982 }
24983 /// PerformMSTORECombine - Resolve truncating stores
24984 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24985                                     const X86Subtarget *Subtarget) {
24986   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24987   if (!Mst->isTruncatingStore())
24988     return SDValue();
24989
24990   EVT VT = Mst->getValue().getValueType();
24991   unsigned NumElems = VT.getVectorNumElements();
24992   EVT StVT = Mst->getMemoryVT();
24993   SDLoc dl(Mst);
24994
24995   assert(StVT != VT && "Cannot truncate to the same type");
24996   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24997   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24998
24999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25000
25001   // The truncating store is legal in some cases. For example
25002   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25003   // are designated for truncate store.
25004   // In this case we don't need any further transformations.
25005   if (TLI.isTruncStoreLegal(VT, StVT))
25006     return SDValue();
25007
25008   // From, To sizes and ElemCount must be pow of two
25009   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25010     "Unexpected size for truncating masked store");
25011   // We are going to use the original vector elt for storing.
25012   // Accumulated smaller vector elements must be a multiple of the store size.
25013   assert (((NumElems * FromSz) % ToSz) == 0 &&
25014           "Unexpected ratio for truncating masked store");
25015
25016   unsigned SizeRatio  = FromSz / ToSz;
25017   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25018
25019   // Create a type on which we perform the shuffle
25020   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25021           StVT.getScalarType(), NumElems*SizeRatio);
25022
25023   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25024
25025   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25026   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25027   for (unsigned i = 0; i != NumElems; ++i)
25028     ShuffleVec[i] = i * SizeRatio;
25029
25030   // Can't shuffle using an illegal type.
25031   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25032          "WideVecVT should be legal");
25033
25034   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25035                                         DAG.getUNDEF(WideVecVT),
25036                                         &ShuffleVec[0]);
25037
25038   SDValue NewMask;
25039   SDValue Mask = Mst->getMask();
25040   if (Mask.getValueType() == VT) {
25041     // Mask and original value have the same type
25042     NewMask = DAG.getBitcast(WideVecVT, Mask);
25043     for (unsigned i = 0; i != NumElems; ++i)
25044       ShuffleVec[i] = i * SizeRatio;
25045     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25046       ShuffleVec[i] = NumElems*SizeRatio;
25047     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25048                                    DAG.getConstant(0, dl, WideVecVT),
25049                                    &ShuffleVec[0]);
25050   }
25051   else {
25052     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25053     unsigned WidenNumElts = NumElems*SizeRatio;
25054     unsigned MaskNumElts = VT.getVectorNumElements();
25055     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25056                                      WidenNumElts);
25057
25058     unsigned NumConcat = WidenNumElts / MaskNumElts;
25059     SmallVector<SDValue, 16> Ops(NumConcat);
25060     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25061     Ops[0] = Mask;
25062     for (unsigned i = 1; i != NumConcat; ++i)
25063       Ops[i] = ZeroVal;
25064
25065     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25066   }
25067
25068   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25069                             NewMask, StVT, Mst->getMemOperand(), false);
25070 }
25071 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25072 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25073                                    const X86Subtarget *Subtarget) {
25074   StoreSDNode *St = cast<StoreSDNode>(N);
25075   EVT VT = St->getValue().getValueType();
25076   EVT StVT = St->getMemoryVT();
25077   SDLoc dl(St);
25078   SDValue StoredVal = St->getOperand(1);
25079   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25080
25081   // If we are saving a concatenation of two XMM registers and 32-byte stores
25082   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25083   bool Fast;
25084   unsigned AddressSpace = St->getAddressSpace();
25085   unsigned Alignment = St->getAlignment();
25086   if (VT.is256BitVector() && StVT == VT &&
25087       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25088                              AddressSpace, Alignment, &Fast) && !Fast) {
25089     unsigned NumElems = VT.getVectorNumElements();
25090     if (NumElems < 2)
25091       return SDValue();
25092
25093     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25094     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25095
25096     SDValue Stride =
25097         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25098     SDValue Ptr0 = St->getBasePtr();
25099     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25100
25101     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25102                                 St->getPointerInfo(), St->isVolatile(),
25103                                 St->isNonTemporal(), Alignment);
25104     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25105                                 St->getPointerInfo(), St->isVolatile(),
25106                                 St->isNonTemporal(),
25107                                 std::min(16U, Alignment));
25108     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25109   }
25110
25111   // Optimize trunc store (of multiple scalars) to shuffle and store.
25112   // First, pack all of the elements in one place. Next, store to memory
25113   // in fewer chunks.
25114   if (St->isTruncatingStore() && VT.isVector()) {
25115     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25116     unsigned NumElems = VT.getVectorNumElements();
25117     assert(StVT != VT && "Cannot truncate to the same type");
25118     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25119     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25120
25121     // The truncating store is legal in some cases. For example
25122     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25123     // are designated for truncate store.
25124     // In this case we don't need any further transformations.
25125     if (TLI.isTruncStoreLegal(VT, StVT))
25126       return SDValue();
25127
25128     // From, To sizes and ElemCount must be pow of two
25129     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25130     // We are going to use the original vector elt for storing.
25131     // Accumulated smaller vector elements must be a multiple of the store size.
25132     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25133
25134     unsigned SizeRatio  = FromSz / ToSz;
25135
25136     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25137
25138     // Create a type on which we perform the shuffle
25139     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25140             StVT.getScalarType(), NumElems*SizeRatio);
25141
25142     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25143
25144     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25145     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25146     for (unsigned i = 0; i != NumElems; ++i)
25147       ShuffleVec[i] = i * SizeRatio;
25148
25149     // Can't shuffle using an illegal type.
25150     if (!TLI.isTypeLegal(WideVecVT))
25151       return SDValue();
25152
25153     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25154                                          DAG.getUNDEF(WideVecVT),
25155                                          &ShuffleVec[0]);
25156     // At this point all of the data is stored at the bottom of the
25157     // register. We now need to save it to mem.
25158
25159     // Find the largest store unit
25160     MVT StoreType = MVT::i8;
25161     for (MVT Tp : MVT::integer_valuetypes()) {
25162       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25163         StoreType = Tp;
25164     }
25165
25166     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25167     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25168         (64 <= NumElems * ToSz))
25169       StoreType = MVT::f64;
25170
25171     // Bitcast the original vector into a vector of store-size units
25172     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25173             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25174     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25175     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25176     SmallVector<SDValue, 8> Chains;
25177     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25178                                         TLI.getPointerTy(DAG.getDataLayout()));
25179     SDValue Ptr = St->getBasePtr();
25180
25181     // Perform one or more big stores into memory.
25182     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25183       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25184                                    StoreType, ShuffWide,
25185                                    DAG.getIntPtrConstant(i, dl));
25186       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25187                                 St->getPointerInfo(), St->isVolatile(),
25188                                 St->isNonTemporal(), St->getAlignment());
25189       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25190       Chains.push_back(Ch);
25191     }
25192
25193     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25194   }
25195
25196   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25197   // the FP state in cases where an emms may be missing.
25198   // A preferable solution to the general problem is to figure out the right
25199   // places to insert EMMS.  This qualifies as a quick hack.
25200
25201   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25202   if (VT.getSizeInBits() != 64)
25203     return SDValue();
25204
25205   const Function *F = DAG.getMachineFunction().getFunction();
25206   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25207   bool F64IsLegal =
25208       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25209   if ((VT.isVector() ||
25210        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25211       isa<LoadSDNode>(St->getValue()) &&
25212       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25213       St->getChain().hasOneUse() && !St->isVolatile()) {
25214     SDNode* LdVal = St->getValue().getNode();
25215     LoadSDNode *Ld = nullptr;
25216     int TokenFactorIndex = -1;
25217     SmallVector<SDValue, 8> Ops;
25218     SDNode* ChainVal = St->getChain().getNode();
25219     // Must be a store of a load.  We currently handle two cases:  the load
25220     // is a direct child, and it's under an intervening TokenFactor.  It is
25221     // possible to dig deeper under nested TokenFactors.
25222     if (ChainVal == LdVal)
25223       Ld = cast<LoadSDNode>(St->getChain());
25224     else if (St->getValue().hasOneUse() &&
25225              ChainVal->getOpcode() == ISD::TokenFactor) {
25226       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25227         if (ChainVal->getOperand(i).getNode() == LdVal) {
25228           TokenFactorIndex = i;
25229           Ld = cast<LoadSDNode>(St->getValue());
25230         } else
25231           Ops.push_back(ChainVal->getOperand(i));
25232       }
25233     }
25234
25235     if (!Ld || !ISD::isNormalLoad(Ld))
25236       return SDValue();
25237
25238     // If this is not the MMX case, i.e. we are just turning i64 load/store
25239     // into f64 load/store, avoid the transformation if there are multiple
25240     // uses of the loaded value.
25241     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25242       return SDValue();
25243
25244     SDLoc LdDL(Ld);
25245     SDLoc StDL(N);
25246     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25247     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25248     // pair instead.
25249     if (Subtarget->is64Bit() || F64IsLegal) {
25250       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25251       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25252                                   Ld->getPointerInfo(), Ld->isVolatile(),
25253                                   Ld->isNonTemporal(), Ld->isInvariant(),
25254                                   Ld->getAlignment());
25255       SDValue NewChain = NewLd.getValue(1);
25256       if (TokenFactorIndex != -1) {
25257         Ops.push_back(NewChain);
25258         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25259       }
25260       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25261                           St->getPointerInfo(),
25262                           St->isVolatile(), St->isNonTemporal(),
25263                           St->getAlignment());
25264     }
25265
25266     // Otherwise, lower to two pairs of 32-bit loads / stores.
25267     SDValue LoAddr = Ld->getBasePtr();
25268     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25269                                  DAG.getConstant(4, LdDL, MVT::i32));
25270
25271     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25272                                Ld->getPointerInfo(),
25273                                Ld->isVolatile(), Ld->isNonTemporal(),
25274                                Ld->isInvariant(), Ld->getAlignment());
25275     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25276                                Ld->getPointerInfo().getWithOffset(4),
25277                                Ld->isVolatile(), Ld->isNonTemporal(),
25278                                Ld->isInvariant(),
25279                                MinAlign(Ld->getAlignment(), 4));
25280
25281     SDValue NewChain = LoLd.getValue(1);
25282     if (TokenFactorIndex != -1) {
25283       Ops.push_back(LoLd);
25284       Ops.push_back(HiLd);
25285       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25286     }
25287
25288     LoAddr = St->getBasePtr();
25289     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25290                          DAG.getConstant(4, StDL, MVT::i32));
25291
25292     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25293                                 St->getPointerInfo(),
25294                                 St->isVolatile(), St->isNonTemporal(),
25295                                 St->getAlignment());
25296     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25297                                 St->getPointerInfo().getWithOffset(4),
25298                                 St->isVolatile(),
25299                                 St->isNonTemporal(),
25300                                 MinAlign(St->getAlignment(), 4));
25301     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25302   }
25303
25304   // This is similar to the above case, but here we handle a scalar 64-bit
25305   // integer store that is extracted from a vector on a 32-bit target.
25306   // If we have SSE2, then we can treat it like a floating-point double
25307   // to get past legalization. The execution dependencies fixup pass will
25308   // choose the optimal machine instruction for the store if this really is
25309   // an integer or v2f32 rather than an f64.
25310   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25311       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25312     SDValue OldExtract = St->getOperand(1);
25313     SDValue ExtOp0 = OldExtract.getOperand(0);
25314     unsigned VecSize = ExtOp0.getValueSizeInBits();
25315     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25316     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25317     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25318                                      BitCast, OldExtract.getOperand(1));
25319     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25320                         St->getPointerInfo(), St->isVolatile(),
25321                         St->isNonTemporal(), St->getAlignment());
25322   }
25323
25324   return SDValue();
25325 }
25326
25327 /// Return 'true' if this vector operation is "horizontal"
25328 /// and return the operands for the horizontal operation in LHS and RHS.  A
25329 /// horizontal operation performs the binary operation on successive elements
25330 /// of its first operand, then on successive elements of its second operand,
25331 /// returning the resulting values in a vector.  For example, if
25332 ///   A = < float a0, float a1, float a2, float a3 >
25333 /// and
25334 ///   B = < float b0, float b1, float b2, float b3 >
25335 /// then the result of doing a horizontal operation on A and B is
25336 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25337 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25338 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25339 /// set to A, RHS to B, and the routine returns 'true'.
25340 /// Note that the binary operation should have the property that if one of the
25341 /// operands is UNDEF then the result is UNDEF.
25342 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25343   // Look for the following pattern: if
25344   //   A = < float a0, float a1, float a2, float a3 >
25345   //   B = < float b0, float b1, float b2, float b3 >
25346   // and
25347   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25348   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25349   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25350   // which is A horizontal-op B.
25351
25352   // At least one of the operands should be a vector shuffle.
25353   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25354       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25355     return false;
25356
25357   MVT VT = LHS.getSimpleValueType();
25358
25359   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25360          "Unsupported vector type for horizontal add/sub");
25361
25362   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25363   // operate independently on 128-bit lanes.
25364   unsigned NumElts = VT.getVectorNumElements();
25365   unsigned NumLanes = VT.getSizeInBits()/128;
25366   unsigned NumLaneElts = NumElts / NumLanes;
25367   assert((NumLaneElts % 2 == 0) &&
25368          "Vector type should have an even number of elements in each lane");
25369   unsigned HalfLaneElts = NumLaneElts/2;
25370
25371   // View LHS in the form
25372   //   LHS = VECTOR_SHUFFLE A, B, LMask
25373   // If LHS is not a shuffle then pretend it is the shuffle
25374   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25375   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25376   // type VT.
25377   SDValue A, B;
25378   SmallVector<int, 16> LMask(NumElts);
25379   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25380     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25381       A = LHS.getOperand(0);
25382     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25383       B = LHS.getOperand(1);
25384     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25385     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25386   } else {
25387     if (LHS.getOpcode() != ISD::UNDEF)
25388       A = LHS;
25389     for (unsigned i = 0; i != NumElts; ++i)
25390       LMask[i] = i;
25391   }
25392
25393   // Likewise, view RHS in the form
25394   //   RHS = VECTOR_SHUFFLE C, D, RMask
25395   SDValue C, D;
25396   SmallVector<int, 16> RMask(NumElts);
25397   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25398     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25399       C = RHS.getOperand(0);
25400     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25401       D = RHS.getOperand(1);
25402     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25403     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25404   } else {
25405     if (RHS.getOpcode() != ISD::UNDEF)
25406       C = RHS;
25407     for (unsigned i = 0; i != NumElts; ++i)
25408       RMask[i] = i;
25409   }
25410
25411   // Check that the shuffles are both shuffling the same vectors.
25412   if (!(A == C && B == D) && !(A == D && B == C))
25413     return false;
25414
25415   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25416   if (!A.getNode() && !B.getNode())
25417     return false;
25418
25419   // If A and B occur in reverse order in RHS, then "swap" them (which means
25420   // rewriting the mask).
25421   if (A != C)
25422     ShuffleVectorSDNode::commuteMask(RMask);
25423
25424   // At this point LHS and RHS are equivalent to
25425   //   LHS = VECTOR_SHUFFLE A, B, LMask
25426   //   RHS = VECTOR_SHUFFLE A, B, RMask
25427   // Check that the masks correspond to performing a horizontal operation.
25428   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25429     for (unsigned i = 0; i != NumLaneElts; ++i) {
25430       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25431
25432       // Ignore any UNDEF components.
25433       if (LIdx < 0 || RIdx < 0 ||
25434           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25435           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25436         continue;
25437
25438       // Check that successive elements are being operated on.  If not, this is
25439       // not a horizontal operation.
25440       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25441       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25442       if (!(LIdx == Index && RIdx == Index + 1) &&
25443           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25444         return false;
25445     }
25446   }
25447
25448   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25449   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25450   return true;
25451 }
25452
25453 /// Do target-specific dag combines on floating point adds.
25454 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25455                                   const X86Subtarget *Subtarget) {
25456   EVT VT = N->getValueType(0);
25457   SDValue LHS = N->getOperand(0);
25458   SDValue RHS = N->getOperand(1);
25459
25460   // Try to synthesize horizontal adds from adds of shuffles.
25461   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25462        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25463       isHorizontalBinOp(LHS, RHS, true))
25464     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25465   return SDValue();
25466 }
25467
25468 /// Do target-specific dag combines on floating point subs.
25469 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25470                                   const X86Subtarget *Subtarget) {
25471   EVT VT = N->getValueType(0);
25472   SDValue LHS = N->getOperand(0);
25473   SDValue RHS = N->getOperand(1);
25474
25475   // Try to synthesize horizontal subs from subs of shuffles.
25476   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25477        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25478       isHorizontalBinOp(LHS, RHS, false))
25479     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25480   return SDValue();
25481 }
25482
25483 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25484 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25485                                  const X86Subtarget *Subtarget) {
25486   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25487
25488   // F[X]OR(0.0, x) -> x
25489   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25490     if (C->getValueAPF().isPosZero())
25491       return N->getOperand(1);
25492
25493   // F[X]OR(x, 0.0) -> x
25494   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25495     if (C->getValueAPF().isPosZero())
25496       return N->getOperand(0);
25497
25498   EVT VT = N->getValueType(0);
25499   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25500     SDLoc dl(N);
25501     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25502     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25503
25504     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25505     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25506     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25507     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25508     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25509   }
25510   return SDValue();
25511 }
25512
25513 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25514 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25515   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25516
25517   // Only perform optimizations if UnsafeMath is used.
25518   if (!DAG.getTarget().Options.UnsafeFPMath)
25519     return SDValue();
25520
25521   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25522   // into FMINC and FMAXC, which are Commutative operations.
25523   unsigned NewOp = 0;
25524   switch (N->getOpcode()) {
25525     default: llvm_unreachable("unknown opcode");
25526     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25527     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25528   }
25529
25530   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25531                      N->getOperand(0), N->getOperand(1));
25532 }
25533
25534 /// Do target-specific dag combines on X86ISD::FAND nodes.
25535 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25536   // FAND(0.0, x) -> 0.0
25537   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25538     if (C->getValueAPF().isPosZero())
25539       return N->getOperand(0);
25540
25541   // FAND(x, 0.0) -> 0.0
25542   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25543     if (C->getValueAPF().isPosZero())
25544       return N->getOperand(1);
25545
25546   return SDValue();
25547 }
25548
25549 /// Do target-specific dag combines on X86ISD::FANDN nodes
25550 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25551   // FANDN(0.0, x) -> x
25552   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25553     if (C->getValueAPF().isPosZero())
25554       return N->getOperand(1);
25555
25556   // FANDN(x, 0.0) -> 0.0
25557   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25558     if (C->getValueAPF().isPosZero())
25559       return N->getOperand(1);
25560
25561   return SDValue();
25562 }
25563
25564 static SDValue PerformBTCombine(SDNode *N,
25565                                 SelectionDAG &DAG,
25566                                 TargetLowering::DAGCombinerInfo &DCI) {
25567   // BT ignores high bits in the bit index operand.
25568   SDValue Op1 = N->getOperand(1);
25569   if (Op1.hasOneUse()) {
25570     unsigned BitWidth = Op1.getValueSizeInBits();
25571     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25572     APInt KnownZero, KnownOne;
25573     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25574                                           !DCI.isBeforeLegalizeOps());
25575     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25576     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25577         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25578       DCI.CommitTargetLoweringOpt(TLO);
25579   }
25580   return SDValue();
25581 }
25582
25583 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25584   SDValue Op = N->getOperand(0);
25585   if (Op.getOpcode() == ISD::BITCAST)
25586     Op = Op.getOperand(0);
25587   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25588   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25589       VT.getVectorElementType().getSizeInBits() ==
25590       OpVT.getVectorElementType().getSizeInBits()) {
25591     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25592   }
25593   return SDValue();
25594 }
25595
25596 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25597                                                const X86Subtarget *Subtarget) {
25598   EVT VT = N->getValueType(0);
25599   if (!VT.isVector())
25600     return SDValue();
25601
25602   SDValue N0 = N->getOperand(0);
25603   SDValue N1 = N->getOperand(1);
25604   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25605   SDLoc dl(N);
25606
25607   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25608   // both SSE and AVX2 since there is no sign-extended shift right
25609   // operation on a vector with 64-bit elements.
25610   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25611   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25612   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25613       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25614     SDValue N00 = N0.getOperand(0);
25615
25616     // EXTLOAD has a better solution on AVX2,
25617     // it may be replaced with X86ISD::VSEXT node.
25618     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25619       if (!ISD::isNormalLoad(N00.getNode()))
25620         return SDValue();
25621
25622     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25623         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25624                                   N00, N1);
25625       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25626     }
25627   }
25628   return SDValue();
25629 }
25630
25631 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25632                                   TargetLowering::DAGCombinerInfo &DCI,
25633                                   const X86Subtarget *Subtarget) {
25634   SDValue N0 = N->getOperand(0);
25635   EVT VT = N->getValueType(0);
25636   EVT SVT = VT.getScalarType();
25637   EVT InVT = N0.getValueType();
25638   EVT InSVT = InVT.getScalarType();
25639   SDLoc DL(N);
25640
25641   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25642   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25643   // This exposes the sext to the sdivrem lowering, so that it directly extends
25644   // from AH (which we otherwise need to do contortions to access).
25645   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25646       InVT == MVT::i8 && VT == MVT::i32) {
25647     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25648     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25649                             N0.getOperand(0), N0.getOperand(1));
25650     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25651     return R.getValue(1);
25652   }
25653
25654   if (!DCI.isBeforeLegalizeOps()) {
25655     if (InVT == MVT::i1) {
25656       SDValue Zero = DAG.getConstant(0, DL, VT);
25657       SDValue AllOnes =
25658         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25659       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25660     }
25661     return SDValue();
25662   }
25663
25664   if (VT.isVector() && Subtarget->hasSSE2()) {
25665     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25666       EVT InVT = N.getValueType();
25667       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25668                                    Size / InVT.getScalarSizeInBits());
25669       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25670                                     DAG.getUNDEF(InVT));
25671       Opnds[0] = N;
25672       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25673     };
25674
25675     // If target-size is less than 128-bits, extend to a type that would extend
25676     // to 128 bits, extend that and extract the original target vector.
25677     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25678         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25679         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25680       unsigned Scale = 128 / VT.getSizeInBits();
25681       EVT ExVT =
25682           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25683       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25684       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25685       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25686                          DAG.getIntPtrConstant(0, DL));
25687     }
25688
25689     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25690     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25691     if (VT.getSizeInBits() == 128 &&
25692         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25693         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25694       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25695       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25696     }
25697
25698     // On pre-AVX2 targets, split into 128-bit nodes of
25699     // ISD::SIGN_EXTEND_VECTOR_INREG.
25700     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25701         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25702         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25703       unsigned NumVecs = VT.getSizeInBits() / 128;
25704       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25705       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25706       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25707
25708       SmallVector<SDValue, 8> Opnds;
25709       for (unsigned i = 0, Offset = 0; i != NumVecs;
25710            ++i, Offset += NumSubElts) {
25711         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25712                                      DAG.getIntPtrConstant(Offset, DL));
25713         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25714         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25715         Opnds.push_back(SrcVec);
25716       }
25717       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25718     }
25719   }
25720
25721   if (!Subtarget->hasFp256())
25722     return SDValue();
25723
25724   if (VT.isVector() && VT.getSizeInBits() == 256)
25725     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25726       return R;
25727
25728   return SDValue();
25729 }
25730
25731 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25732                                  const X86Subtarget* Subtarget) {
25733   SDLoc dl(N);
25734   EVT VT = N->getValueType(0);
25735
25736   // Let legalize expand this if it isn't a legal type yet.
25737   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25738     return SDValue();
25739
25740   EVT ScalarVT = VT.getScalarType();
25741   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25742       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25743        !Subtarget->hasAVX512()))
25744     return SDValue();
25745
25746   SDValue A = N->getOperand(0);
25747   SDValue B = N->getOperand(1);
25748   SDValue C = N->getOperand(2);
25749
25750   bool NegA = (A.getOpcode() == ISD::FNEG);
25751   bool NegB = (B.getOpcode() == ISD::FNEG);
25752   bool NegC = (C.getOpcode() == ISD::FNEG);
25753
25754   // Negative multiplication when NegA xor NegB
25755   bool NegMul = (NegA != NegB);
25756   if (NegA)
25757     A = A.getOperand(0);
25758   if (NegB)
25759     B = B.getOperand(0);
25760   if (NegC)
25761     C = C.getOperand(0);
25762
25763   unsigned Opcode;
25764   if (!NegMul)
25765     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25766   else
25767     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25768
25769   return DAG.getNode(Opcode, dl, VT, A, B, C);
25770 }
25771
25772 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25773                                   TargetLowering::DAGCombinerInfo &DCI,
25774                                   const X86Subtarget *Subtarget) {
25775   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25776   //           (and (i32 x86isd::setcc_carry), 1)
25777   // This eliminates the zext. This transformation is necessary because
25778   // ISD::SETCC is always legalized to i8.
25779   SDLoc dl(N);
25780   SDValue N0 = N->getOperand(0);
25781   EVT VT = N->getValueType(0);
25782
25783   if (N0.getOpcode() == ISD::AND &&
25784       N0.hasOneUse() &&
25785       N0.getOperand(0).hasOneUse()) {
25786     SDValue N00 = N0.getOperand(0);
25787     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25788       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25789       if (!C || C->getZExtValue() != 1)
25790         return SDValue();
25791       return DAG.getNode(ISD::AND, dl, VT,
25792                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25793                                      N00.getOperand(0), N00.getOperand(1)),
25794                          DAG.getConstant(1, dl, VT));
25795     }
25796   }
25797
25798   if (N0.getOpcode() == ISD::TRUNCATE &&
25799       N0.hasOneUse() &&
25800       N0.getOperand(0).hasOneUse()) {
25801     SDValue N00 = N0.getOperand(0);
25802     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25803       return DAG.getNode(ISD::AND, dl, VT,
25804                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25805                                      N00.getOperand(0), N00.getOperand(1)),
25806                          DAG.getConstant(1, dl, VT));
25807     }
25808   }
25809
25810   if (VT.is256BitVector())
25811     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25812       return R;
25813
25814   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25815   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25816   // This exposes the zext to the udivrem lowering, so that it directly extends
25817   // from AH (which we otherwise need to do contortions to access).
25818   if (N0.getOpcode() == ISD::UDIVREM &&
25819       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25820       (VT == MVT::i32 || VT == MVT::i64)) {
25821     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25822     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25823                             N0.getOperand(0), N0.getOperand(1));
25824     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25825     return R.getValue(1);
25826   }
25827
25828   return SDValue();
25829 }
25830
25831 // Optimize x == -y --> x+y == 0
25832 //          x != -y --> x+y != 0
25833 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25834                                       const X86Subtarget* Subtarget) {
25835   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25836   SDValue LHS = N->getOperand(0);
25837   SDValue RHS = N->getOperand(1);
25838   EVT VT = N->getValueType(0);
25839   SDLoc DL(N);
25840
25841   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25842     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25843       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25844         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25845                                    LHS.getOperand(1));
25846         return DAG.getSetCC(DL, N->getValueType(0), addV,
25847                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25848       }
25849   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25850     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25851       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25852         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25853                                    RHS.getOperand(1));
25854         return DAG.getSetCC(DL, N->getValueType(0), addV,
25855                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25856       }
25857
25858   if (VT.getScalarType() == MVT::i1 &&
25859       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25860     bool IsSEXT0 =
25861         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25862         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25863     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25864
25865     if (!IsSEXT0 || !IsVZero1) {
25866       // Swap the operands and update the condition code.
25867       std::swap(LHS, RHS);
25868       CC = ISD::getSetCCSwappedOperands(CC);
25869
25870       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25871                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25872       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25873     }
25874
25875     if (IsSEXT0 && IsVZero1) {
25876       assert(VT == LHS.getOperand(0).getValueType() &&
25877              "Uexpected operand type");
25878       if (CC == ISD::SETGT)
25879         return DAG.getConstant(0, DL, VT);
25880       if (CC == ISD::SETLE)
25881         return DAG.getConstant(1, DL, VT);
25882       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25883         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25884
25885       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25886              "Unexpected condition code!");
25887       return LHS.getOperand(0);
25888     }
25889   }
25890
25891   return SDValue();
25892 }
25893
25894 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25895                                          SelectionDAG &DAG) {
25896   SDLoc dl(Load);
25897   MVT VT = Load->getSimpleValueType(0);
25898   MVT EVT = VT.getVectorElementType();
25899   SDValue Addr = Load->getOperand(1);
25900   SDValue NewAddr = DAG.getNode(
25901       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25902       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25903                       Addr.getSimpleValueType()));
25904
25905   SDValue NewLoad =
25906       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25907                   DAG.getMachineFunction().getMachineMemOperand(
25908                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25909   return NewLoad;
25910 }
25911
25912 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25913                                       const X86Subtarget *Subtarget) {
25914   SDLoc dl(N);
25915   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25916   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25917          "X86insertps is only defined for v4x32");
25918
25919   SDValue Ld = N->getOperand(1);
25920   if (MayFoldLoad(Ld)) {
25921     // Extract the countS bits from the immediate so we can get the proper
25922     // address when narrowing the vector load to a specific element.
25923     // When the second source op is a memory address, insertps doesn't use
25924     // countS and just gets an f32 from that address.
25925     unsigned DestIndex =
25926         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25927
25928     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25929
25930     // Create this as a scalar to vector to match the instruction pattern.
25931     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25932     // countS bits are ignored when loading from memory on insertps, which
25933     // means we don't need to explicitly set them to 0.
25934     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25935                        LoadScalarToVector, N->getOperand(2));
25936   }
25937   return SDValue();
25938 }
25939
25940 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25941   SDValue V0 = N->getOperand(0);
25942   SDValue V1 = N->getOperand(1);
25943   SDLoc DL(N);
25944   EVT VT = N->getValueType(0);
25945
25946   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25947   // operands and changing the mask to 1. This saves us a bunch of
25948   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25949   // x86InstrInfo knows how to commute this back after instruction selection
25950   // if it would help register allocation.
25951
25952   // TODO: If optimizing for size or a processor that doesn't suffer from
25953   // partial register update stalls, this should be transformed into a MOVSD
25954   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25955
25956   if (VT == MVT::v2f64)
25957     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25958       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25959         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25960         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25961       }
25962
25963   return SDValue();
25964 }
25965
25966 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25967 // as "sbb reg,reg", since it can be extended without zext and produces
25968 // an all-ones bit which is more useful than 0/1 in some cases.
25969 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25970                                MVT VT) {
25971   if (VT == MVT::i8)
25972     return DAG.getNode(ISD::AND, DL, VT,
25973                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25974                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25975                                    EFLAGS),
25976                        DAG.getConstant(1, DL, VT));
25977   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25978   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25979                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25980                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25981                                  EFLAGS));
25982 }
25983
25984 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25985 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25986                                    TargetLowering::DAGCombinerInfo &DCI,
25987                                    const X86Subtarget *Subtarget) {
25988   SDLoc DL(N);
25989   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25990   SDValue EFLAGS = N->getOperand(1);
25991
25992   if (CC == X86::COND_A) {
25993     // Try to convert COND_A into COND_B in an attempt to facilitate
25994     // materializing "setb reg".
25995     //
25996     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25997     // cannot take an immediate as its first operand.
25998     //
25999     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26000         EFLAGS.getValueType().isInteger() &&
26001         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26002       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26003                                    EFLAGS.getNode()->getVTList(),
26004                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26005       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26006       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26007     }
26008   }
26009
26010   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26011   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26012   // cases.
26013   if (CC == X86::COND_B)
26014     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26015
26016   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26017     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26018     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26019   }
26020
26021   return SDValue();
26022 }
26023
26024 // Optimize branch condition evaluation.
26025 //
26026 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26027                                     TargetLowering::DAGCombinerInfo &DCI,
26028                                     const X86Subtarget *Subtarget) {
26029   SDLoc DL(N);
26030   SDValue Chain = N->getOperand(0);
26031   SDValue Dest = N->getOperand(1);
26032   SDValue EFLAGS = N->getOperand(3);
26033   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26034
26035   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26036     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26037     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26038                        Flags);
26039   }
26040
26041   return SDValue();
26042 }
26043
26044 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26045                                                          SelectionDAG &DAG) {
26046   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26047   // optimize away operation when it's from a constant.
26048   //
26049   // The general transformation is:
26050   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26051   //       AND(VECTOR_CMP(x,y), constant2)
26052   //    constant2 = UNARYOP(constant)
26053
26054   // Early exit if this isn't a vector operation, the operand of the
26055   // unary operation isn't a bitwise AND, or if the sizes of the operations
26056   // aren't the same.
26057   EVT VT = N->getValueType(0);
26058   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26059       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26060       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26061     return SDValue();
26062
26063   // Now check that the other operand of the AND is a constant. We could
26064   // make the transformation for non-constant splats as well, but it's unclear
26065   // that would be a benefit as it would not eliminate any operations, just
26066   // perform one more step in scalar code before moving to the vector unit.
26067   if (BuildVectorSDNode *BV =
26068           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26069     // Bail out if the vector isn't a constant.
26070     if (!BV->isConstant())
26071       return SDValue();
26072
26073     // Everything checks out. Build up the new and improved node.
26074     SDLoc DL(N);
26075     EVT IntVT = BV->getValueType(0);
26076     // Create a new constant of the appropriate type for the transformed
26077     // DAG.
26078     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26079     // The AND node needs bitcasts to/from an integer vector type around it.
26080     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26081     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26082                                  N->getOperand(0)->getOperand(0), MaskConst);
26083     SDValue Res = DAG.getBitcast(VT, NewAnd);
26084     return Res;
26085   }
26086
26087   return SDValue();
26088 }
26089
26090 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26091                                         const X86Subtarget *Subtarget) {
26092   SDValue Op0 = N->getOperand(0);
26093   EVT VT = N->getValueType(0);
26094   EVT InVT = Op0.getValueType();
26095   EVT InSVT = InVT.getScalarType();
26096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26097
26098   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26099   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26100   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26101     SDLoc dl(N);
26102     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26103                                  InVT.getVectorNumElements());
26104     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26105
26106     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26107       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26108
26109     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26110   }
26111
26112   return SDValue();
26113 }
26114
26115 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26116                                         const X86Subtarget *Subtarget) {
26117   // First try to optimize away the conversion entirely when it's
26118   // conditionally from a constant. Vectors only.
26119   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26120     return Res;
26121
26122   // Now move on to more general possibilities.
26123   SDValue Op0 = N->getOperand(0);
26124   EVT VT = N->getValueType(0);
26125   EVT InVT = Op0.getValueType();
26126   EVT InSVT = InVT.getScalarType();
26127
26128   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26129   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26130   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26131     SDLoc dl(N);
26132     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26133                                  InVT.getVectorNumElements());
26134     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26135     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26136   }
26137
26138   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26139   // a 32-bit target where SSE doesn't support i64->FP operations.
26140   if (Op0.getOpcode() == ISD::LOAD) {
26141     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26142     EVT LdVT = Ld->getValueType(0);
26143
26144     // This transformation is not supported if the result type is f16
26145     if (VT == MVT::f16)
26146       return SDValue();
26147
26148     if (!Ld->isVolatile() && !VT.isVector() &&
26149         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26150         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26151       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26152           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26153       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26154       return FILDChain;
26155     }
26156   }
26157   return SDValue();
26158 }
26159
26160 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26161 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26162                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26163   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26164   // the result is either zero or one (depending on the input carry bit).
26165   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26166   if (X86::isZeroNode(N->getOperand(0)) &&
26167       X86::isZeroNode(N->getOperand(1)) &&
26168       // We don't have a good way to replace an EFLAGS use, so only do this when
26169       // dead right now.
26170       SDValue(N, 1).use_empty()) {
26171     SDLoc DL(N);
26172     EVT VT = N->getValueType(0);
26173     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26174     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26175                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26176                                            DAG.getConstant(X86::COND_B, DL,
26177                                                            MVT::i8),
26178                                            N->getOperand(2)),
26179                                DAG.getConstant(1, DL, VT));
26180     return DCI.CombineTo(N, Res1, CarryOut);
26181   }
26182
26183   return SDValue();
26184 }
26185
26186 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26187 //      (add Y, (setne X, 0)) -> sbb -1, Y
26188 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26189 //      (sub (setne X, 0), Y) -> adc -1, Y
26190 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26191   SDLoc DL(N);
26192
26193   // Look through ZExts.
26194   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26195   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26196     return SDValue();
26197
26198   SDValue SetCC = Ext.getOperand(0);
26199   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26200     return SDValue();
26201
26202   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26203   if (CC != X86::COND_E && CC != X86::COND_NE)
26204     return SDValue();
26205
26206   SDValue Cmp = SetCC.getOperand(1);
26207   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26208       !X86::isZeroNode(Cmp.getOperand(1)) ||
26209       !Cmp.getOperand(0).getValueType().isInteger())
26210     return SDValue();
26211
26212   SDValue CmpOp0 = Cmp.getOperand(0);
26213   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26214                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26215
26216   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26217   if (CC == X86::COND_NE)
26218     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26219                        DL, OtherVal.getValueType(), OtherVal,
26220                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26221                        NewCmp);
26222   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26223                      DL, OtherVal.getValueType(), OtherVal,
26224                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26225 }
26226
26227 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26228 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26229                                  const X86Subtarget *Subtarget) {
26230   EVT VT = N->getValueType(0);
26231   SDValue Op0 = N->getOperand(0);
26232   SDValue Op1 = N->getOperand(1);
26233
26234   // Try to synthesize horizontal adds from adds of shuffles.
26235   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26236        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26237       isHorizontalBinOp(Op0, Op1, true))
26238     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26239
26240   return OptimizeConditionalInDecrement(N, DAG);
26241 }
26242
26243 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26244                                  const X86Subtarget *Subtarget) {
26245   SDValue Op0 = N->getOperand(0);
26246   SDValue Op1 = N->getOperand(1);
26247
26248   // X86 can't encode an immediate LHS of a sub. See if we can push the
26249   // negation into a preceding instruction.
26250   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26251     // If the RHS of the sub is a XOR with one use and a constant, invert the
26252     // immediate. Then add one to the LHS of the sub so we can turn
26253     // X-Y -> X+~Y+1, saving one register.
26254     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26255         isa<ConstantSDNode>(Op1.getOperand(1))) {
26256       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26257       EVT VT = Op0.getValueType();
26258       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26259                                    Op1.getOperand(0),
26260                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26261       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26262                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26263     }
26264   }
26265
26266   // Try to synthesize horizontal adds from adds of shuffles.
26267   EVT VT = N->getValueType(0);
26268   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26269        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26270       isHorizontalBinOp(Op0, Op1, true))
26271     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26272
26273   return OptimizeConditionalInDecrement(N, DAG);
26274 }
26275
26276 /// performVZEXTCombine - Performs build vector combines
26277 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26278                                    TargetLowering::DAGCombinerInfo &DCI,
26279                                    const X86Subtarget *Subtarget) {
26280   SDLoc DL(N);
26281   MVT VT = N->getSimpleValueType(0);
26282   SDValue Op = N->getOperand(0);
26283   MVT OpVT = Op.getSimpleValueType();
26284   MVT OpEltVT = OpVT.getVectorElementType();
26285   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26286
26287   // (vzext (bitcast (vzext (x)) -> (vzext x)
26288   SDValue V = Op;
26289   while (V.getOpcode() == ISD::BITCAST)
26290     V = V.getOperand(0);
26291
26292   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26293     MVT InnerVT = V.getSimpleValueType();
26294     MVT InnerEltVT = InnerVT.getVectorElementType();
26295
26296     // If the element sizes match exactly, we can just do one larger vzext. This
26297     // is always an exact type match as vzext operates on integer types.
26298     if (OpEltVT == InnerEltVT) {
26299       assert(OpVT == InnerVT && "Types must match for vzext!");
26300       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26301     }
26302
26303     // The only other way we can combine them is if only a single element of the
26304     // inner vzext is used in the input to the outer vzext.
26305     if (InnerEltVT.getSizeInBits() < InputBits)
26306       return SDValue();
26307
26308     // In this case, the inner vzext is completely dead because we're going to
26309     // only look at bits inside of the low element. Just do the outer vzext on
26310     // a bitcast of the input to the inner.
26311     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26312   }
26313
26314   // Check if we can bypass extracting and re-inserting an element of an input
26315   // vector. Essentially:
26316   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26317   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26318       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26319       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26320     SDValue ExtractedV = V.getOperand(0);
26321     SDValue OrigV = ExtractedV.getOperand(0);
26322     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26323       if (ExtractIdx->getZExtValue() == 0) {
26324         MVT OrigVT = OrigV.getSimpleValueType();
26325         // Extract a subvector if necessary...
26326         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26327           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26328           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26329                                     OrigVT.getVectorNumElements() / Ratio);
26330           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26331                               DAG.getIntPtrConstant(0, DL));
26332         }
26333         Op = DAG.getBitcast(OpVT, OrigV);
26334         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26335       }
26336   }
26337
26338   return SDValue();
26339 }
26340
26341 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26342                                              DAGCombinerInfo &DCI) const {
26343   SelectionDAG &DAG = DCI.DAG;
26344   switch (N->getOpcode()) {
26345   default: break;
26346   case ISD::EXTRACT_VECTOR_ELT:
26347     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26348   case ISD::VSELECT:
26349   case ISD::SELECT:
26350   case X86ISD::SHRUNKBLEND:
26351     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26352   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26353   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26354   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26355   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26356   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26357   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26358   case ISD::SHL:
26359   case ISD::SRA:
26360   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26361   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26362   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26363   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26364   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26365   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26366   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26367   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26368   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26369   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26370   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26371   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26372   case X86ISD::FXOR:
26373   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26374   case X86ISD::FMIN:
26375   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26376   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26377   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26378   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26379   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26380   case ISD::ANY_EXTEND:
26381   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26382   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26383   case ISD::SIGN_EXTEND_INREG:
26384     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26385   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26386   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26387   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26388   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26389   case X86ISD::SHUFP:       // Handle all target specific shuffles
26390   case X86ISD::PALIGNR:
26391   case X86ISD::UNPCKH:
26392   case X86ISD::UNPCKL:
26393   case X86ISD::MOVHLPS:
26394   case X86ISD::MOVLHPS:
26395   case X86ISD::PSHUFB:
26396   case X86ISD::PSHUFD:
26397   case X86ISD::PSHUFHW:
26398   case X86ISD::PSHUFLW:
26399   case X86ISD::MOVSS:
26400   case X86ISD::MOVSD:
26401   case X86ISD::VPERMILPI:
26402   case X86ISD::VPERM2X128:
26403   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26404   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26405   case X86ISD::INSERTPS: {
26406     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26407       return PerformINSERTPSCombine(N, DAG, Subtarget);
26408     break;
26409   }
26410   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26411   }
26412
26413   return SDValue();
26414 }
26415
26416 /// isTypeDesirableForOp - Return true if the target has native support for
26417 /// the specified value type and it is 'desirable' to use the type for the
26418 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26419 /// instruction encodings are longer and some i16 instructions are slow.
26420 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26421   if (!isTypeLegal(VT))
26422     return false;
26423   if (VT != MVT::i16)
26424     return true;
26425
26426   switch (Opc) {
26427   default:
26428     return true;
26429   case ISD::LOAD:
26430   case ISD::SIGN_EXTEND:
26431   case ISD::ZERO_EXTEND:
26432   case ISD::ANY_EXTEND:
26433   case ISD::SHL:
26434   case ISD::SRL:
26435   case ISD::SUB:
26436   case ISD::ADD:
26437   case ISD::MUL:
26438   case ISD::AND:
26439   case ISD::OR:
26440   case ISD::XOR:
26441     return false;
26442   }
26443 }
26444
26445 /// IsDesirableToPromoteOp - This method query the target whether it is
26446 /// beneficial for dag combiner to promote the specified node. If true, it
26447 /// should return the desired promotion type by reference.
26448 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26449   EVT VT = Op.getValueType();
26450   if (VT != MVT::i16)
26451     return false;
26452
26453   bool Promote = false;
26454   bool Commute = false;
26455   switch (Op.getOpcode()) {
26456   default: break;
26457   case ISD::LOAD: {
26458     LoadSDNode *LD = cast<LoadSDNode>(Op);
26459     // If the non-extending load has a single use and it's not live out, then it
26460     // might be folded.
26461     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26462                                                      Op.hasOneUse()*/) {
26463       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26464              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26465         // The only case where we'd want to promote LOAD (rather then it being
26466         // promoted as an operand is when it's only use is liveout.
26467         if (UI->getOpcode() != ISD::CopyToReg)
26468           return false;
26469       }
26470     }
26471     Promote = true;
26472     break;
26473   }
26474   case ISD::SIGN_EXTEND:
26475   case ISD::ZERO_EXTEND:
26476   case ISD::ANY_EXTEND:
26477     Promote = true;
26478     break;
26479   case ISD::SHL:
26480   case ISD::SRL: {
26481     SDValue N0 = Op.getOperand(0);
26482     // Look out for (store (shl (load), x)).
26483     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26484       return false;
26485     Promote = true;
26486     break;
26487   }
26488   case ISD::ADD:
26489   case ISD::MUL:
26490   case ISD::AND:
26491   case ISD::OR:
26492   case ISD::XOR:
26493     Commute = true;
26494     // fallthrough
26495   case ISD::SUB: {
26496     SDValue N0 = Op.getOperand(0);
26497     SDValue N1 = Op.getOperand(1);
26498     if (!Commute && MayFoldLoad(N1))
26499       return false;
26500     // Avoid disabling potential load folding opportunities.
26501     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26502       return false;
26503     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26504       return false;
26505     Promote = true;
26506   }
26507   }
26508
26509   PVT = MVT::i32;
26510   return Promote;
26511 }
26512
26513 //===----------------------------------------------------------------------===//
26514 //                           X86 Inline Assembly Support
26515 //===----------------------------------------------------------------------===//
26516
26517 // Helper to match a string separated by whitespace.
26518 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26519   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26520
26521   for (StringRef Piece : Pieces) {
26522     if (!S.startswith(Piece)) // Check if the piece matches.
26523       return false;
26524
26525     S = S.substr(Piece.size());
26526     StringRef::size_type Pos = S.find_first_not_of(" \t");
26527     if (Pos == 0) // We matched a prefix.
26528       return false;
26529
26530     S = S.substr(Pos);
26531   }
26532
26533   return S.empty();
26534 }
26535
26536 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26537
26538   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26539     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26540         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26541         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26542
26543       if (AsmPieces.size() == 3)
26544         return true;
26545       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26546         return true;
26547     }
26548   }
26549   return false;
26550 }
26551
26552 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26553   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26554
26555   std::string AsmStr = IA->getAsmString();
26556
26557   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26558   if (!Ty || Ty->getBitWidth() % 16 != 0)
26559     return false;
26560
26561   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26562   SmallVector<StringRef, 4> AsmPieces;
26563   SplitString(AsmStr, AsmPieces, ";\n");
26564
26565   switch (AsmPieces.size()) {
26566   default: return false;
26567   case 1:
26568     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26569     // we will turn this bswap into something that will be lowered to logical
26570     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26571     // lower so don't worry about this.
26572     // bswap $0
26573     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26574         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26575         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26576         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26577         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26578         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26579       // No need to check constraints, nothing other than the equivalent of
26580       // "=r,0" would be valid here.
26581       return IntrinsicLowering::LowerToByteSwap(CI);
26582     }
26583
26584     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26585     if (CI->getType()->isIntegerTy(16) &&
26586         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26587         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26588          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26589       AsmPieces.clear();
26590       StringRef ConstraintsStr = IA->getConstraintString();
26591       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26592       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26593       if (clobbersFlagRegisters(AsmPieces))
26594         return IntrinsicLowering::LowerToByteSwap(CI);
26595     }
26596     break;
26597   case 3:
26598     if (CI->getType()->isIntegerTy(32) &&
26599         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26600         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26601         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26602         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26603       AsmPieces.clear();
26604       StringRef ConstraintsStr = IA->getConstraintString();
26605       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26606       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26607       if (clobbersFlagRegisters(AsmPieces))
26608         return IntrinsicLowering::LowerToByteSwap(CI);
26609     }
26610
26611     if (CI->getType()->isIntegerTy(64)) {
26612       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26613       if (Constraints.size() >= 2 &&
26614           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26615           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26616         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26617         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26618             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26619             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26620           return IntrinsicLowering::LowerToByteSwap(CI);
26621       }
26622     }
26623     break;
26624   }
26625   return false;
26626 }
26627
26628 /// getConstraintType - Given a constraint letter, return the type of
26629 /// constraint it is for this target.
26630 X86TargetLowering::ConstraintType
26631 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26632   if (Constraint.size() == 1) {
26633     switch (Constraint[0]) {
26634     case 'R':
26635     case 'q':
26636     case 'Q':
26637     case 'f':
26638     case 't':
26639     case 'u':
26640     case 'y':
26641     case 'x':
26642     case 'Y':
26643     case 'l':
26644       return C_RegisterClass;
26645     case 'a':
26646     case 'b':
26647     case 'c':
26648     case 'd':
26649     case 'S':
26650     case 'D':
26651     case 'A':
26652       return C_Register;
26653     case 'I':
26654     case 'J':
26655     case 'K':
26656     case 'L':
26657     case 'M':
26658     case 'N':
26659     case 'G':
26660     case 'C':
26661     case 'e':
26662     case 'Z':
26663       return C_Other;
26664     default:
26665       break;
26666     }
26667   }
26668   return TargetLowering::getConstraintType(Constraint);
26669 }
26670
26671 /// Examine constraint type and operand type and determine a weight value.
26672 /// This object must already have been set up with the operand type
26673 /// and the current alternative constraint selected.
26674 TargetLowering::ConstraintWeight
26675   X86TargetLowering::getSingleConstraintMatchWeight(
26676     AsmOperandInfo &info, const char *constraint) const {
26677   ConstraintWeight weight = CW_Invalid;
26678   Value *CallOperandVal = info.CallOperandVal;
26679     // If we don't have a value, we can't do a match,
26680     // but allow it at the lowest weight.
26681   if (!CallOperandVal)
26682     return CW_Default;
26683   Type *type = CallOperandVal->getType();
26684   // Look at the constraint type.
26685   switch (*constraint) {
26686   default:
26687     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26688   case 'R':
26689   case 'q':
26690   case 'Q':
26691   case 'a':
26692   case 'b':
26693   case 'c':
26694   case 'd':
26695   case 'S':
26696   case 'D':
26697   case 'A':
26698     if (CallOperandVal->getType()->isIntegerTy())
26699       weight = CW_SpecificReg;
26700     break;
26701   case 'f':
26702   case 't':
26703   case 'u':
26704     if (type->isFloatingPointTy())
26705       weight = CW_SpecificReg;
26706     break;
26707   case 'y':
26708     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26709       weight = CW_SpecificReg;
26710     break;
26711   case 'x':
26712   case 'Y':
26713     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26714         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26715       weight = CW_Register;
26716     break;
26717   case 'I':
26718     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26719       if (C->getZExtValue() <= 31)
26720         weight = CW_Constant;
26721     }
26722     break;
26723   case 'J':
26724     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26725       if (C->getZExtValue() <= 63)
26726         weight = CW_Constant;
26727     }
26728     break;
26729   case 'K':
26730     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26731       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26732         weight = CW_Constant;
26733     }
26734     break;
26735   case 'L':
26736     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26737       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26738         weight = CW_Constant;
26739     }
26740     break;
26741   case 'M':
26742     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26743       if (C->getZExtValue() <= 3)
26744         weight = CW_Constant;
26745     }
26746     break;
26747   case 'N':
26748     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26749       if (C->getZExtValue() <= 0xff)
26750         weight = CW_Constant;
26751     }
26752     break;
26753   case 'G':
26754   case 'C':
26755     if (isa<ConstantFP>(CallOperandVal)) {
26756       weight = CW_Constant;
26757     }
26758     break;
26759   case 'e':
26760     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26761       if ((C->getSExtValue() >= -0x80000000LL) &&
26762           (C->getSExtValue() <= 0x7fffffffLL))
26763         weight = CW_Constant;
26764     }
26765     break;
26766   case 'Z':
26767     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26768       if (C->getZExtValue() <= 0xffffffff)
26769         weight = CW_Constant;
26770     }
26771     break;
26772   }
26773   return weight;
26774 }
26775
26776 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26777 /// with another that has more specific requirements based on the type of the
26778 /// corresponding operand.
26779 const char *X86TargetLowering::
26780 LowerXConstraint(EVT ConstraintVT) const {
26781   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26782   // 'f' like normal targets.
26783   if (ConstraintVT.isFloatingPoint()) {
26784     if (Subtarget->hasSSE2())
26785       return "Y";
26786     if (Subtarget->hasSSE1())
26787       return "x";
26788   }
26789
26790   return TargetLowering::LowerXConstraint(ConstraintVT);
26791 }
26792
26793 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26794 /// vector.  If it is invalid, don't add anything to Ops.
26795 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26796                                                      std::string &Constraint,
26797                                                      std::vector<SDValue>&Ops,
26798                                                      SelectionDAG &DAG) const {
26799   SDValue Result;
26800
26801   // Only support length 1 constraints for now.
26802   if (Constraint.length() > 1) return;
26803
26804   char ConstraintLetter = Constraint[0];
26805   switch (ConstraintLetter) {
26806   default: break;
26807   case 'I':
26808     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26809       if (C->getZExtValue() <= 31) {
26810         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26811                                        Op.getValueType());
26812         break;
26813       }
26814     }
26815     return;
26816   case 'J':
26817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26818       if (C->getZExtValue() <= 63) {
26819         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26820                                        Op.getValueType());
26821         break;
26822       }
26823     }
26824     return;
26825   case 'K':
26826     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26827       if (isInt<8>(C->getSExtValue())) {
26828         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26829                                        Op.getValueType());
26830         break;
26831       }
26832     }
26833     return;
26834   case 'L':
26835     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26836       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26837           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26838         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26839                                        Op.getValueType());
26840         break;
26841       }
26842     }
26843     return;
26844   case 'M':
26845     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26846       if (C->getZExtValue() <= 3) {
26847         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26848                                        Op.getValueType());
26849         break;
26850       }
26851     }
26852     return;
26853   case 'N':
26854     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26855       if (C->getZExtValue() <= 255) {
26856         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26857                                        Op.getValueType());
26858         break;
26859       }
26860     }
26861     return;
26862   case 'O':
26863     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26864       if (C->getZExtValue() <= 127) {
26865         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26866                                        Op.getValueType());
26867         break;
26868       }
26869     }
26870     return;
26871   case 'e': {
26872     // 32-bit signed value
26873     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26874       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26875                                            C->getSExtValue())) {
26876         // Widen to 64 bits here to get it sign extended.
26877         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26878         break;
26879       }
26880     // FIXME gcc accepts some relocatable values here too, but only in certain
26881     // memory models; it's complicated.
26882     }
26883     return;
26884   }
26885   case 'Z': {
26886     // 32-bit unsigned value
26887     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26888       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26889                                            C->getZExtValue())) {
26890         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26891                                        Op.getValueType());
26892         break;
26893       }
26894     }
26895     // FIXME gcc accepts some relocatable values here too, but only in certain
26896     // memory models; it's complicated.
26897     return;
26898   }
26899   case 'i': {
26900     // Literal immediates are always ok.
26901     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26902       // Widen to 64 bits here to get it sign extended.
26903       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26904       break;
26905     }
26906
26907     // In any sort of PIC mode addresses need to be computed at runtime by
26908     // adding in a register or some sort of table lookup.  These can't
26909     // be used as immediates.
26910     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26911       return;
26912
26913     // If we are in non-pic codegen mode, we allow the address of a global (with
26914     // an optional displacement) to be used with 'i'.
26915     GlobalAddressSDNode *GA = nullptr;
26916     int64_t Offset = 0;
26917
26918     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26919     while (1) {
26920       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26921         Offset += GA->getOffset();
26922         break;
26923       } else if (Op.getOpcode() == ISD::ADD) {
26924         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26925           Offset += C->getZExtValue();
26926           Op = Op.getOperand(0);
26927           continue;
26928         }
26929       } else if (Op.getOpcode() == ISD::SUB) {
26930         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26931           Offset += -C->getZExtValue();
26932           Op = Op.getOperand(0);
26933           continue;
26934         }
26935       }
26936
26937       // Otherwise, this isn't something we can handle, reject it.
26938       return;
26939     }
26940
26941     const GlobalValue *GV = GA->getGlobal();
26942     // If we require an extra load to get this address, as in PIC mode, we
26943     // can't accept it.
26944     if (isGlobalStubReference(
26945             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26946       return;
26947
26948     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26949                                         GA->getValueType(0), Offset);
26950     break;
26951   }
26952   }
26953
26954   if (Result.getNode()) {
26955     Ops.push_back(Result);
26956     return;
26957   }
26958   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26959 }
26960
26961 std::pair<unsigned, const TargetRegisterClass *>
26962 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26963                                                 StringRef Constraint,
26964                                                 MVT VT) const {
26965   // First, see if this is a constraint that directly corresponds to an LLVM
26966   // register class.
26967   if (Constraint.size() == 1) {
26968     // GCC Constraint Letters
26969     switch (Constraint[0]) {
26970     default: break;
26971       // TODO: Slight differences here in allocation order and leaving
26972       // RIP in the class. Do they matter any more here than they do
26973       // in the normal allocation?
26974     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26975       if (Subtarget->is64Bit()) {
26976         if (VT == MVT::i32 || VT == MVT::f32)
26977           return std::make_pair(0U, &X86::GR32RegClass);
26978         if (VT == MVT::i16)
26979           return std::make_pair(0U, &X86::GR16RegClass);
26980         if (VT == MVT::i8 || VT == MVT::i1)
26981           return std::make_pair(0U, &X86::GR8RegClass);
26982         if (VT == MVT::i64 || VT == MVT::f64)
26983           return std::make_pair(0U, &X86::GR64RegClass);
26984         break;
26985       }
26986       // 32-bit fallthrough
26987     case 'Q':   // Q_REGS
26988       if (VT == MVT::i32 || VT == MVT::f32)
26989         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26990       if (VT == MVT::i16)
26991         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26992       if (VT == MVT::i8 || VT == MVT::i1)
26993         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26994       if (VT == MVT::i64)
26995         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26996       break;
26997     case 'r':   // GENERAL_REGS
26998     case 'l':   // INDEX_REGS
26999       if (VT == MVT::i8 || VT == MVT::i1)
27000         return std::make_pair(0U, &X86::GR8RegClass);
27001       if (VT == MVT::i16)
27002         return std::make_pair(0U, &X86::GR16RegClass);
27003       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27004         return std::make_pair(0U, &X86::GR32RegClass);
27005       return std::make_pair(0U, &X86::GR64RegClass);
27006     case 'R':   // LEGACY_REGS
27007       if (VT == MVT::i8 || VT == MVT::i1)
27008         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27009       if (VT == MVT::i16)
27010         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27011       if (VT == MVT::i32 || !Subtarget->is64Bit())
27012         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27013       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27014     case 'f':  // FP Stack registers.
27015       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27016       // value to the correct fpstack register class.
27017       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27018         return std::make_pair(0U, &X86::RFP32RegClass);
27019       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27020         return std::make_pair(0U, &X86::RFP64RegClass);
27021       return std::make_pair(0U, &X86::RFP80RegClass);
27022     case 'y':   // MMX_REGS if MMX allowed.
27023       if (!Subtarget->hasMMX()) break;
27024       return std::make_pair(0U, &X86::VR64RegClass);
27025     case 'Y':   // SSE_REGS if SSE2 allowed
27026       if (!Subtarget->hasSSE2()) break;
27027       // FALL THROUGH.
27028     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27029       if (!Subtarget->hasSSE1()) break;
27030
27031       switch (VT.SimpleTy) {
27032       default: break;
27033       // Scalar SSE types.
27034       case MVT::f32:
27035       case MVT::i32:
27036         return std::make_pair(0U, &X86::FR32RegClass);
27037       case MVT::f64:
27038       case MVT::i64:
27039         return std::make_pair(0U, &X86::FR64RegClass);
27040       // Vector types.
27041       case MVT::v16i8:
27042       case MVT::v8i16:
27043       case MVT::v4i32:
27044       case MVT::v2i64:
27045       case MVT::v4f32:
27046       case MVT::v2f64:
27047         return std::make_pair(0U, &X86::VR128RegClass);
27048       // AVX types.
27049       case MVT::v32i8:
27050       case MVT::v16i16:
27051       case MVT::v8i32:
27052       case MVT::v4i64:
27053       case MVT::v8f32:
27054       case MVT::v4f64:
27055         return std::make_pair(0U, &X86::VR256RegClass);
27056       case MVT::v8f64:
27057       case MVT::v16f32:
27058       case MVT::v16i32:
27059       case MVT::v8i64:
27060         return std::make_pair(0U, &X86::VR512RegClass);
27061       }
27062       break;
27063     }
27064   }
27065
27066   // Use the default implementation in TargetLowering to convert the register
27067   // constraint into a member of a register class.
27068   std::pair<unsigned, const TargetRegisterClass*> Res;
27069   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27070
27071   // Not found as a standard register?
27072   if (!Res.second) {
27073     // Map st(0) -> st(7) -> ST0
27074     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27075         tolower(Constraint[1]) == 's' &&
27076         tolower(Constraint[2]) == 't' &&
27077         Constraint[3] == '(' &&
27078         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27079         Constraint[5] == ')' &&
27080         Constraint[6] == '}') {
27081
27082       Res.first = X86::FP0+Constraint[4]-'0';
27083       Res.second = &X86::RFP80RegClass;
27084       return Res;
27085     }
27086
27087     // GCC allows "st(0)" to be called just plain "st".
27088     if (StringRef("{st}").equals_lower(Constraint)) {
27089       Res.first = X86::FP0;
27090       Res.second = &X86::RFP80RegClass;
27091       return Res;
27092     }
27093
27094     // flags -> EFLAGS
27095     if (StringRef("{flags}").equals_lower(Constraint)) {
27096       Res.first = X86::EFLAGS;
27097       Res.second = &X86::CCRRegClass;
27098       return Res;
27099     }
27100
27101     // 'A' means EAX + EDX.
27102     if (Constraint == "A") {
27103       Res.first = X86::EAX;
27104       Res.second = &X86::GR32_ADRegClass;
27105       return Res;
27106     }
27107     return Res;
27108   }
27109
27110   // Otherwise, check to see if this is a register class of the wrong value
27111   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27112   // turn into {ax},{dx}.
27113   // MVT::Other is used to specify clobber names.
27114   if (Res.second->hasType(VT) || VT == MVT::Other)
27115     return Res;   // Correct type already, nothing to do.
27116
27117   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27118   // return "eax". This should even work for things like getting 64bit integer
27119   // registers when given an f64 type.
27120   const TargetRegisterClass *Class = Res.second;
27121   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27122       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27123     unsigned Size = VT.getSizeInBits();
27124     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27125                                   : Size == 16 ? MVT::i16
27126                                   : Size == 32 ? MVT::i32
27127                                   : Size == 64 ? MVT::i64
27128                                   : MVT::Other;
27129     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27130     if (DestReg > 0) {
27131       Res.first = DestReg;
27132       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27133                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27134                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27135                  : &X86::GR64RegClass;
27136       assert(Res.second->contains(Res.first) && "Register in register class");
27137     } else {
27138       // No register found/type mismatch.
27139       Res.first = 0;
27140       Res.second = nullptr;
27141     }
27142   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27143              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27144              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27145              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27146              Class == &X86::VR512RegClass) {
27147     // Handle references to XMM physical registers that got mapped into the
27148     // wrong class.  This can happen with constraints like {xmm0} where the
27149     // target independent register mapper will just pick the first match it can
27150     // find, ignoring the required type.
27151
27152     if (VT == MVT::f32 || VT == MVT::i32)
27153       Res.second = &X86::FR32RegClass;
27154     else if (VT == MVT::f64 || VT == MVT::i64)
27155       Res.second = &X86::FR64RegClass;
27156     else if (X86::VR128RegClass.hasType(VT))
27157       Res.second = &X86::VR128RegClass;
27158     else if (X86::VR256RegClass.hasType(VT))
27159       Res.second = &X86::VR256RegClass;
27160     else if (X86::VR512RegClass.hasType(VT))
27161       Res.second = &X86::VR512RegClass;
27162     else {
27163       // Type mismatch and not a clobber: Return an error;
27164       Res.first = 0;
27165       Res.second = nullptr;
27166     }
27167   }
27168
27169   return Res;
27170 }
27171
27172 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27173                                             const AddrMode &AM, Type *Ty,
27174                                             unsigned AS) const {
27175   // Scaling factors are not free at all.
27176   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27177   // will take 2 allocations in the out of order engine instead of 1
27178   // for plain addressing mode, i.e. inst (reg1).
27179   // E.g.,
27180   // vaddps (%rsi,%drx), %ymm0, %ymm1
27181   // Requires two allocations (one for the load, one for the computation)
27182   // whereas:
27183   // vaddps (%rsi), %ymm0, %ymm1
27184   // Requires just 1 allocation, i.e., freeing allocations for other operations
27185   // and having less micro operations to execute.
27186   //
27187   // For some X86 architectures, this is even worse because for instance for
27188   // stores, the complex addressing mode forces the instruction to use the
27189   // "load" ports instead of the dedicated "store" port.
27190   // E.g., on Haswell:
27191   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27192   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27193   if (isLegalAddressingMode(DL, AM, Ty, AS))
27194     // Scale represents reg2 * scale, thus account for 1
27195     // as soon as we use a second register.
27196     return AM.Scale != 0;
27197   return -1;
27198 }
27199
27200 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27201   // Integer division on x86 is expensive. However, when aggressively optimizing
27202   // for code size, we prefer to use a div instruction, as it is usually smaller
27203   // than the alternative sequence.
27204   // The exception to this is vector division. Since x86 doesn't have vector
27205   // integer division, leaving the division as-is is a loss even in terms of
27206   // size, because it will have to be scalarized, while the alternative code
27207   // sequence can be performed in vector form.
27208   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27209                                    Attribute::MinSize);
27210   return OptSize && !VT.isVector();
27211 }