[safestack] Fast access to the unsafe stack pointer on AArch64/Android.
[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->hasXOP()) {
1054     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1055     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1056     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1057     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1058     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1059     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1060     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1061     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1062   }
1063
1064   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1065     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1066     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1067     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1068     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1069     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1070     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1071
1072     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1073     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1074     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1075
1076     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1077     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1078     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1081     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1082     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1083     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1084     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1085     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1086     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1087     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1088
1089     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1090     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1091     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1092     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1093     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1094     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1095     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1096     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1097     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1098     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1099     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1100     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1101
1102     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1103     // even though v8i16 is a legal type.
1104     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1105     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1106     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1107
1108     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1109     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1110     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1111
1112     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1113     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1114
1115     for (MVT VT : MVT::fp_vector_valuetypes())
1116       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1117
1118     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1119     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1120
1121     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1122     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1123
1124     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1125     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1126
1127     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1128     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1129     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1130     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1131
1132     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1133     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1134     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1135
1136     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1137     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1138     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1139     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1140     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1141     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1142     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1143     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1144     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1145     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1146     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1147     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1148
1149     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1150     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1151     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1152     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1153
1154     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1155     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1156     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1157     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1158     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1159     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1160     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1161     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1162
1163     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1164       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1165       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1166       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1168       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1169       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1170     }
1171
1172     if (Subtarget->hasInt256()) {
1173       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1174       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1175       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1177
1178       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1179       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1180       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1182
1183       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1184       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1185       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1186       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1187
1188       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1189       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1190       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1191       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1192
1193       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1194       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1195       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1196       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1197       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1198       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1199       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1200       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1201       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1202       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1203       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1204       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1205
1206       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1207       // when we have a 256bit-wide blend with immediate.
1208       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1209
1210       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1211       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1212       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1213       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1214       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1215       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1216       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1217
1218       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1219       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1220       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1221       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1222       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1223       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1224     } else {
1225       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1226       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1227       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1228       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1229
1230       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1231       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1232       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1233       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1234
1235       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1236       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1237       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1238       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1239
1240       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1241       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1242       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1243       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1244       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1245       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1246       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1247       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1248       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1249       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1250       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1251       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1252     }
1253
1254     // In the customized shift lowering, the legal cases in AVX2 will be
1255     // recognized.
1256     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1257     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1258
1259     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1260     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1261
1262     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1263     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1264
1265     // Custom lower several nodes for 256-bit types.
1266     for (MVT VT : MVT::vector_valuetypes()) {
1267       if (VT.getScalarSizeInBits() >= 32) {
1268         setOperationAction(ISD::MLOAD,  VT, Legal);
1269         setOperationAction(ISD::MSTORE, VT, Legal);
1270       }
1271       // Extract subvector is special because the value type
1272       // (result) is 128-bit but the source is 256-bit wide.
1273       if (VT.is128BitVector()) {
1274         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1275       }
1276       // Do not attempt to custom lower other non-256-bit vectors
1277       if (!VT.is256BitVector())
1278         continue;
1279
1280       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1281       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1282       setOperationAction(ISD::VSELECT,            VT, Custom);
1283       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1284       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1286       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1287       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1288     }
1289
1290     if (Subtarget->hasInt256())
1291       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1292
1293     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1295       MVT VT = (MVT::SimpleValueType)i;
1296
1297       // Do not attempt to promote non-256-bit vectors
1298       if (!VT.is256BitVector())
1299         continue;
1300
1301       setOperationAction(ISD::AND,    VT, Promote);
1302       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1303       setOperationAction(ISD::OR,     VT, Promote);
1304       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1305       setOperationAction(ISD::XOR,    VT, Promote);
1306       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1307       setOperationAction(ISD::LOAD,   VT, Promote);
1308       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1309       setOperationAction(ISD::SELECT, VT, Promote);
1310       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1311     }
1312   }
1313
1314   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1315     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1316     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1317     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1318     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1319
1320     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1321     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1322     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1323
1324     for (MVT VT : MVT::fp_vector_valuetypes())
1325       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1326
1327     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1328     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1329     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1330     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1331     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1332     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1333     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1334     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1335     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1336     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1337     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1338     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1339
1340     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1341     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1342     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1343     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1344     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1345     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1346     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1347     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1348     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1349     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1350     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1351     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1352     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1353     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1354
1355     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1356     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1357     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1358     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1359     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1360     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1361
1362     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1363     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1364     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1365     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1366     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1367     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1368     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1369     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1370
1371     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1374     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1376     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1377     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1378     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1379     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1380     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1383     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1384     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1385     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1386     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1387
1388     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1389     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1390     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1391     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1392     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1393     if (Subtarget->hasVLX()){
1394       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1395       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1396       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1397       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1398       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1399
1400       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1401       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1402       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1403       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1404       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1405     }
1406     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1407     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1408     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1409     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1410     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1411     if (Subtarget->hasDQI()) {
1412       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1413       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1414
1415       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1416       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1417       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1418       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1419       if (Subtarget->hasVLX()) {
1420         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1421         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1422         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1423         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1424         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1425         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1426         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1427         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1428       }
1429     }
1430     if (Subtarget->hasVLX()) {
1431       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1432       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1433       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1434       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1435       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1436       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1437       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1438       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1439     }
1440     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1441     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1442     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1443     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1444     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1445     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1446     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1447     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1448     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1449     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1450     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1451     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1452     if (Subtarget->hasDQI()) {
1453       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1454       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1455     }
1456     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1457     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1458     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1459     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1460     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1461     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1462     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1463     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1464     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1465     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1466
1467     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1468     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1469     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1470     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1471     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1472
1473     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1474     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1475
1476     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1477
1478     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1479     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1480     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1481     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1482     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1483     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1484     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1485     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1486     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1487     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1488     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1489
1490     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1491     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1492     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1493     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1494     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1495     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1496     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1497     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1498
1499     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1500     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1501
1502     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1503     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1504
1505     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1506
1507     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1508     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1509
1510     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1511     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1512
1513     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1514     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1515
1516     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1517     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1518     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1519     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1520     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1521     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1522
1523     if (Subtarget->hasCDI()) {
1524       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1525       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1526       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1527       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1528
1529       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1530       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1531       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1532       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1533       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1534       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1535       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1536       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1537
1538       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1539       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1540
1541       if (Subtarget->hasVLX()) {
1542         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1543         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1544         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1545         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1546         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1547         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1548         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1549         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1550
1551         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1552         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1553         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1554         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1555       } else {
1556         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1557         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1558         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1559         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1560         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1561         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1562         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1563         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1564       }
1565     } // Subtarget->hasCDI()
1566
1567     if (Subtarget->hasDQI()) {
1568       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1569       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1570       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1571     }
1572     // Custom lower several nodes.
1573     for (MVT VT : MVT::vector_valuetypes()) {
1574       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1575       if (EltSize == 1) {
1576         setOperationAction(ISD::AND, VT, Legal);
1577         setOperationAction(ISD::OR,  VT, Legal);
1578         setOperationAction(ISD::XOR,  VT, Legal);
1579       }
1580       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1581         setOperationAction(ISD::MGATHER,  VT, Custom);
1582         setOperationAction(ISD::MSCATTER, VT, Custom);
1583       }
1584       // Extract subvector is special because the value type
1585       // (result) is 256/128-bit but the source is 512-bit wide.
1586       if (VT.is128BitVector() || VT.is256BitVector()) {
1587         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1588       }
1589       if (VT.getVectorElementType() == MVT::i1)
1590         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1591
1592       // Do not attempt to custom lower other non-512-bit vectors
1593       if (!VT.is512BitVector())
1594         continue;
1595
1596       if (EltSize >= 32) {
1597         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1598         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1599         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1600         setOperationAction(ISD::VSELECT,             VT, Legal);
1601         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1602         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1603         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1604         setOperationAction(ISD::MLOAD,               VT, Legal);
1605         setOperationAction(ISD::MSTORE,              VT, Legal);
1606       }
1607     }
1608     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1609       MVT VT = (MVT::SimpleValueType)i;
1610
1611       // Do not attempt to promote non-512-bit vectors.
1612       if (!VT.is512BitVector())
1613         continue;
1614
1615       setOperationAction(ISD::SELECT, VT, Promote);
1616       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1617     }
1618   }// has  AVX-512
1619
1620   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1621     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1622     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1623
1624     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1625     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1626
1627     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1628     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1629     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1630     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1631     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1632     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1633     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1634     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1635     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1636     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1637     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1638     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1639     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1640     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1641     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1642     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1643     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1644     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1645     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1646     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1647     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1648     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1649     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1650     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1651     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1652     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1653     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1654     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1655     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1656     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1657     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1658     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1659     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1660     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1661     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1662     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1663     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1664     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1665     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1666     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1667     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1668     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1669
1670     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1671     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1672     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1673     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1674     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1675     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1676     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1677     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1678
1679     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1680     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1681     if (Subtarget->hasVLX())
1682       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1683
1684     if (Subtarget->hasCDI()) {
1685       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1686       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1687       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1688       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1689     }
1690
1691     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1692       const MVT VT = (MVT::SimpleValueType)i;
1693
1694       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1695
1696       // Do not attempt to promote non-512-bit vectors.
1697       if (!VT.is512BitVector())
1698         continue;
1699
1700       if (EltSize < 32) {
1701         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1702         setOperationAction(ISD::VSELECT,             VT, Legal);
1703       }
1704     }
1705   }
1706
1707   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1708     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1709     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1710
1711     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1712     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1713     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1714     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1715     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1716     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1717     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1718     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1719     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1720     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1721     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1722     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1723
1724     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1725     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1726     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1727     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1728     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1729     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1730     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1731     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1732
1733     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1734     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1735     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1736     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1737     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1738     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1739     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1740     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1741   }
1742
1743   // We want to custom lower some of our intrinsics.
1744   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1745   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1746   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1747   if (!Subtarget->is64Bit())
1748     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1749
1750   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1751   // handle type legalization for these operations here.
1752   //
1753   // FIXME: We really should do custom legalization for addition and
1754   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1755   // than generic legalization for 64-bit multiplication-with-overflow, though.
1756   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1757     // Add/Sub/Mul with overflow operations are custom lowered.
1758     MVT VT = IntVTs[i];
1759     setOperationAction(ISD::SADDO, VT, Custom);
1760     setOperationAction(ISD::UADDO, VT, Custom);
1761     setOperationAction(ISD::SSUBO, VT, Custom);
1762     setOperationAction(ISD::USUBO, VT, Custom);
1763     setOperationAction(ISD::SMULO, VT, Custom);
1764     setOperationAction(ISD::UMULO, VT, Custom);
1765   }
1766
1767   if (!Subtarget->is64Bit()) {
1768     // These libcalls are not available in 32-bit.
1769     setLibcallName(RTLIB::SHL_I128, nullptr);
1770     setLibcallName(RTLIB::SRL_I128, nullptr);
1771     setLibcallName(RTLIB::SRA_I128, nullptr);
1772   }
1773
1774   // Combine sin / cos into one node or libcall if possible.
1775   if (Subtarget->hasSinCos()) {
1776     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1777     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1778     if (Subtarget->isTargetDarwin()) {
1779       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1780       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1781       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1782       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1783     }
1784   }
1785
1786   if (Subtarget->isTargetWin64()) {
1787     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1788     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1789     setOperationAction(ISD::SREM, MVT::i128, Custom);
1790     setOperationAction(ISD::UREM, MVT::i128, Custom);
1791     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1792     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1793   }
1794
1795   // We have target-specific dag combine patterns for the following nodes:
1796   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1797   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1798   setTargetDAGCombine(ISD::BITCAST);
1799   setTargetDAGCombine(ISD::VSELECT);
1800   setTargetDAGCombine(ISD::SELECT);
1801   setTargetDAGCombine(ISD::SHL);
1802   setTargetDAGCombine(ISD::SRA);
1803   setTargetDAGCombine(ISD::SRL);
1804   setTargetDAGCombine(ISD::OR);
1805   setTargetDAGCombine(ISD::AND);
1806   setTargetDAGCombine(ISD::ADD);
1807   setTargetDAGCombine(ISD::FADD);
1808   setTargetDAGCombine(ISD::FSUB);
1809   setTargetDAGCombine(ISD::FMA);
1810   setTargetDAGCombine(ISD::SUB);
1811   setTargetDAGCombine(ISD::LOAD);
1812   setTargetDAGCombine(ISD::MLOAD);
1813   setTargetDAGCombine(ISD::STORE);
1814   setTargetDAGCombine(ISD::MSTORE);
1815   setTargetDAGCombine(ISD::ZERO_EXTEND);
1816   setTargetDAGCombine(ISD::ANY_EXTEND);
1817   setTargetDAGCombine(ISD::SIGN_EXTEND);
1818   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1819   setTargetDAGCombine(ISD::SINT_TO_FP);
1820   setTargetDAGCombine(ISD::UINT_TO_FP);
1821   setTargetDAGCombine(ISD::SETCC);
1822   setTargetDAGCombine(ISD::BUILD_VECTOR);
1823   setTargetDAGCombine(ISD::MUL);
1824   setTargetDAGCombine(ISD::XOR);
1825
1826   computeRegisterProperties(Subtarget->getRegisterInfo());
1827
1828   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1829   MaxStoresPerMemsetOptSize = 8;
1830   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1831   MaxStoresPerMemcpyOptSize = 4;
1832   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1833   MaxStoresPerMemmoveOptSize = 4;
1834   setPrefLoopAlignment(4); // 2^4 bytes.
1835
1836   // A predictable cmov does not hurt on an in-order CPU.
1837   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1838   PredictableSelectIsExpensive = !Subtarget->isAtom();
1839   EnableExtLdPromotion = true;
1840   setPrefFunctionAlignment(4); // 2^4 bytes.
1841
1842   verifyIntrinsicTables();
1843 }
1844
1845 // This has so far only been implemented for 64-bit MachO.
1846 bool X86TargetLowering::useLoadStackGuardNode() const {
1847   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1848 }
1849
1850 TargetLoweringBase::LegalizeTypeAction
1851 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1852   if (ExperimentalVectorWideningLegalization &&
1853       VT.getVectorNumElements() != 1 &&
1854       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1855     return TypeWidenVector;
1856
1857   return TargetLoweringBase::getPreferredVectorAction(VT);
1858 }
1859
1860 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1861                                           EVT VT) const {
1862   if (!VT.isVector())
1863     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1864
1865   const unsigned NumElts = VT.getVectorNumElements();
1866   const EVT EltVT = VT.getVectorElementType();
1867   if (VT.is512BitVector()) {
1868     if (Subtarget->hasAVX512())
1869       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1870           EltVT == MVT::f32 || EltVT == MVT::f64)
1871         switch(NumElts) {
1872         case  8: return MVT::v8i1;
1873         case 16: return MVT::v16i1;
1874       }
1875     if (Subtarget->hasBWI())
1876       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1877         switch(NumElts) {
1878         case 32: return MVT::v32i1;
1879         case 64: return MVT::v64i1;
1880       }
1881   }
1882
1883   if (VT.is256BitVector() || VT.is128BitVector()) {
1884     if (Subtarget->hasVLX())
1885       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1886           EltVT == MVT::f32 || EltVT == MVT::f64)
1887         switch(NumElts) {
1888         case 2: return MVT::v2i1;
1889         case 4: return MVT::v4i1;
1890         case 8: return MVT::v8i1;
1891       }
1892     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1893       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1894         switch(NumElts) {
1895         case  8: return MVT::v8i1;
1896         case 16: return MVT::v16i1;
1897         case 32: return MVT::v32i1;
1898       }
1899   }
1900
1901   return VT.changeVectorElementTypeToInteger();
1902 }
1903
1904 /// Helper for getByValTypeAlignment to determine
1905 /// the desired ByVal argument alignment.
1906 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1907   if (MaxAlign == 16)
1908     return;
1909   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1910     if (VTy->getBitWidth() == 128)
1911       MaxAlign = 16;
1912   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1913     unsigned EltAlign = 0;
1914     getMaxByValAlign(ATy->getElementType(), EltAlign);
1915     if (EltAlign > MaxAlign)
1916       MaxAlign = EltAlign;
1917   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1918     for (auto *EltTy : STy->elements()) {
1919       unsigned EltAlign = 0;
1920       getMaxByValAlign(EltTy, EltAlign);
1921       if (EltAlign > MaxAlign)
1922         MaxAlign = EltAlign;
1923       if (MaxAlign == 16)
1924         break;
1925     }
1926   }
1927 }
1928
1929 /// Return the desired alignment for ByVal aggregate
1930 /// function arguments in the caller parameter area. For X86, aggregates
1931 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1932 /// are at 4-byte boundaries.
1933 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1934                                                   const DataLayout &DL) const {
1935   if (Subtarget->is64Bit()) {
1936     // Max of 8 and alignment of type.
1937     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1938     if (TyAlign > 8)
1939       return TyAlign;
1940     return 8;
1941   }
1942
1943   unsigned Align = 4;
1944   if (Subtarget->hasSSE1())
1945     getMaxByValAlign(Ty, Align);
1946   return Align;
1947 }
1948
1949 /// Returns the target specific optimal type for load
1950 /// and store operations as a result of memset, memcpy, and memmove
1951 /// lowering. If DstAlign is zero that means it's safe to destination
1952 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1953 /// means there isn't a need to check it against alignment requirement,
1954 /// probably because the source does not need to be loaded. If 'IsMemset' is
1955 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1956 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1957 /// source is constant so it does not need to be loaded.
1958 /// It returns EVT::Other if the type should be determined using generic
1959 /// target-independent logic.
1960 EVT
1961 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1962                                        unsigned DstAlign, unsigned SrcAlign,
1963                                        bool IsMemset, bool ZeroMemset,
1964                                        bool MemcpyStrSrc,
1965                                        MachineFunction &MF) const {
1966   const Function *F = MF.getFunction();
1967   if ((!IsMemset || ZeroMemset) &&
1968       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1969     if (Size >= 16 &&
1970         (!Subtarget->isUnalignedMem16Slow() ||
1971          ((DstAlign == 0 || DstAlign >= 16) &&
1972           (SrcAlign == 0 || SrcAlign >= 16)))) {
1973       if (Size >= 32) {
1974         // FIXME: Check if unaligned 32-byte accesses are slow.
1975         if (Subtarget->hasInt256())
1976           return MVT::v8i32;
1977         if (Subtarget->hasFp256())
1978           return MVT::v8f32;
1979       }
1980       if (Subtarget->hasSSE2())
1981         return MVT::v4i32;
1982       if (Subtarget->hasSSE1())
1983         return MVT::v4f32;
1984     } else if (!MemcpyStrSrc && Size >= 8 &&
1985                !Subtarget->is64Bit() &&
1986                Subtarget->hasSSE2()) {
1987       // Do not use f64 to lower memcpy if source is string constant. It's
1988       // better to use i32 to avoid the loads.
1989       return MVT::f64;
1990     }
1991   }
1992   // This is a compromise. If we reach here, unaligned accesses may be slow on
1993   // this target. However, creating smaller, aligned accesses could be even
1994   // slower and would certainly be a lot more code.
1995   if (Subtarget->is64Bit() && Size >= 8)
1996     return MVT::i64;
1997   return MVT::i32;
1998 }
1999
2000 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2001   if (VT == MVT::f32)
2002     return X86ScalarSSEf32;
2003   else if (VT == MVT::f64)
2004     return X86ScalarSSEf64;
2005   return true;
2006 }
2007
2008 bool
2009 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2010                                                   unsigned,
2011                                                   unsigned,
2012                                                   bool *Fast) const {
2013   if (Fast) {
2014     switch (VT.getSizeInBits()) {
2015     default:
2016       // 8-byte and under are always assumed to be fast.
2017       *Fast = true;
2018       break;
2019     case 128:
2020       *Fast = !Subtarget->isUnalignedMem16Slow();
2021       break;
2022     case 256:
2023       *Fast = !Subtarget->isUnalignedMem32Slow();
2024       break;
2025     // TODO: What about AVX-512 (512-bit) accesses?
2026     }
2027   }
2028   // Misaligned accesses of any size are always allowed.
2029   return true;
2030 }
2031
2032 /// Return the entry encoding for a jump table in the
2033 /// current function.  The returned value is a member of the
2034 /// MachineJumpTableInfo::JTEntryKind enum.
2035 unsigned X86TargetLowering::getJumpTableEncoding() const {
2036   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2037   // symbol.
2038   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2039       Subtarget->isPICStyleGOT())
2040     return MachineJumpTableInfo::EK_Custom32;
2041
2042   // Otherwise, use the normal jump table encoding heuristics.
2043   return TargetLowering::getJumpTableEncoding();
2044 }
2045
2046 bool X86TargetLowering::useSoftFloat() const {
2047   return Subtarget->useSoftFloat();
2048 }
2049
2050 const MCExpr *
2051 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2052                                              const MachineBasicBlock *MBB,
2053                                              unsigned uid,MCContext &Ctx) const{
2054   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2055          Subtarget->isPICStyleGOT());
2056   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2057   // entries.
2058   return MCSymbolRefExpr::create(MBB->getSymbol(),
2059                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2060 }
2061
2062 /// Returns relocation base for the given PIC jumptable.
2063 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2064                                                     SelectionDAG &DAG) const {
2065   if (!Subtarget->is64Bit())
2066     // This doesn't have SDLoc associated with it, but is not really the
2067     // same as a Register.
2068     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2069                        getPointerTy(DAG.getDataLayout()));
2070   return Table;
2071 }
2072
2073 /// This returns the relocation base for the given PIC jumptable,
2074 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2075 const MCExpr *X86TargetLowering::
2076 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2077                              MCContext &Ctx) const {
2078   // X86-64 uses RIP relative addressing based on the jump table label.
2079   if (Subtarget->isPICStyleRIPRel())
2080     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2081
2082   // Otherwise, the reference is relative to the PIC base.
2083   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2084 }
2085
2086 std::pair<const TargetRegisterClass *, uint8_t>
2087 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2088                                            MVT VT) const {
2089   const TargetRegisterClass *RRC = nullptr;
2090   uint8_t Cost = 1;
2091   switch (VT.SimpleTy) {
2092   default:
2093     return TargetLowering::findRepresentativeClass(TRI, VT);
2094   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2095     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2096     break;
2097   case MVT::x86mmx:
2098     RRC = &X86::VR64RegClass;
2099     break;
2100   case MVT::f32: case MVT::f64:
2101   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2102   case MVT::v4f32: case MVT::v2f64:
2103   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2104   case MVT::v4f64:
2105     RRC = &X86::VR128RegClass;
2106     break;
2107   }
2108   return std::make_pair(RRC, Cost);
2109 }
2110
2111 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2112                                                unsigned &Offset) const {
2113   if (!Subtarget->isTargetLinux())
2114     return false;
2115
2116   if (Subtarget->is64Bit()) {
2117     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2118     Offset = 0x28;
2119     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2120       AddressSpace = 256;
2121     else
2122       AddressSpace = 257;
2123   } else {
2124     // %gs:0x14 on i386
2125     Offset = 0x14;
2126     AddressSpace = 256;
2127   }
2128   return true;
2129 }
2130
2131 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2132   if (!Subtarget->isTargetAndroid())
2133     return TargetLowering::getSafeStackPointerLocation(IRB);
2134
2135   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2136   // definition of TLS_SLOT_SAFESTACK in
2137   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2138   unsigned AddressSpace, Offset;
2139   if (Subtarget->is64Bit()) {
2140     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2141     Offset = 0x48;
2142     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2143       AddressSpace = 256;
2144     else
2145       AddressSpace = 257;
2146   } else {
2147     // %gs:0x24 on i386
2148     Offset = 0x24;
2149     AddressSpace = 256;
2150   }
2151
2152   return ConstantExpr::getIntToPtr(
2153       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2154       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2155 }
2156
2157 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2158                                             unsigned DestAS) const {
2159   assert(SrcAS != DestAS && "Expected different address spaces!");
2160
2161   return SrcAS < 256 && DestAS < 256;
2162 }
2163
2164 //===----------------------------------------------------------------------===//
2165 //               Return Value Calling Convention Implementation
2166 //===----------------------------------------------------------------------===//
2167
2168 #include "X86GenCallingConv.inc"
2169
2170 bool X86TargetLowering::CanLowerReturn(
2171     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2172     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2173   SmallVector<CCValAssign, 16> RVLocs;
2174   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2175   return CCInfo.CheckReturn(Outs, RetCC_X86);
2176 }
2177
2178 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2179   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2180   return ScratchRegs;
2181 }
2182
2183 SDValue
2184 X86TargetLowering::LowerReturn(SDValue Chain,
2185                                CallingConv::ID CallConv, bool isVarArg,
2186                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2187                                const SmallVectorImpl<SDValue> &OutVals,
2188                                SDLoc dl, SelectionDAG &DAG) const {
2189   MachineFunction &MF = DAG.getMachineFunction();
2190   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2191
2192   SmallVector<CCValAssign, 16> RVLocs;
2193   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2194   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2195
2196   SDValue Flag;
2197   SmallVector<SDValue, 6> RetOps;
2198   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2199   // Operand #1 = Bytes To Pop
2200   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2201                    MVT::i16));
2202
2203   // Copy the result values into the output registers.
2204   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2205     CCValAssign &VA = RVLocs[i];
2206     assert(VA.isRegLoc() && "Can only return in registers!");
2207     SDValue ValToCopy = OutVals[i];
2208     EVT ValVT = ValToCopy.getValueType();
2209
2210     // Promote values to the appropriate types.
2211     if (VA.getLocInfo() == CCValAssign::SExt)
2212       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2213     else if (VA.getLocInfo() == CCValAssign::ZExt)
2214       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2215     else if (VA.getLocInfo() == CCValAssign::AExt) {
2216       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2217         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2218       else
2219         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2220     }
2221     else if (VA.getLocInfo() == CCValAssign::BCvt)
2222       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2223
2224     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2225            "Unexpected FP-extend for return value.");
2226
2227     // If this is x86-64, and we disabled SSE, we can't return FP values,
2228     // or SSE or MMX vectors.
2229     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2230          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2231           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2232       report_fatal_error("SSE register return with SSE disabled");
2233     }
2234     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2235     // llvm-gcc has never done it right and no one has noticed, so this
2236     // should be OK for now.
2237     if (ValVT == MVT::f64 &&
2238         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2239       report_fatal_error("SSE2 register return with SSE2 disabled");
2240
2241     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2242     // the RET instruction and handled by the FP Stackifier.
2243     if (VA.getLocReg() == X86::FP0 ||
2244         VA.getLocReg() == X86::FP1) {
2245       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2246       // change the value to the FP stack register class.
2247       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2248         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2249       RetOps.push_back(ValToCopy);
2250       // Don't emit a copytoreg.
2251       continue;
2252     }
2253
2254     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2255     // which is returned in RAX / RDX.
2256     if (Subtarget->is64Bit()) {
2257       if (ValVT == MVT::x86mmx) {
2258         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2259           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2260           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2261                                   ValToCopy);
2262           // If we don't have SSE2 available, convert to v4f32 so the generated
2263           // register is legal.
2264           if (!Subtarget->hasSSE2())
2265             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2266         }
2267       }
2268     }
2269
2270     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2271     Flag = Chain.getValue(1);
2272     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2273   }
2274
2275   // All x86 ABIs require that for returning structs by value we copy
2276   // the sret argument into %rax/%eax (depending on ABI) for the return.
2277   // We saved the argument into a virtual register in the entry block,
2278   // so now we copy the value out and into %rax/%eax.
2279   //
2280   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2281   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2282   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2283   // either case FuncInfo->setSRetReturnReg() will have been called.
2284   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2285     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2286                                      getPointerTy(MF.getDataLayout()));
2287
2288     unsigned RetValReg
2289         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2290           X86::RAX : X86::EAX;
2291     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2292     Flag = Chain.getValue(1);
2293
2294     // RAX/EAX now acts like a return value.
2295     RetOps.push_back(
2296         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2297   }
2298
2299   RetOps[0] = Chain;  // Update chain.
2300
2301   // Add the flag if we have it.
2302   if (Flag.getNode())
2303     RetOps.push_back(Flag);
2304
2305   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2306 }
2307
2308 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2309   if (N->getNumValues() != 1)
2310     return false;
2311   if (!N->hasNUsesOfValue(1, 0))
2312     return false;
2313
2314   SDValue TCChain = Chain;
2315   SDNode *Copy = *N->use_begin();
2316   if (Copy->getOpcode() == ISD::CopyToReg) {
2317     // If the copy has a glue operand, we conservatively assume it isn't safe to
2318     // perform a tail call.
2319     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2320       return false;
2321     TCChain = Copy->getOperand(0);
2322   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2323     return false;
2324
2325   bool HasRet = false;
2326   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2327        UI != UE; ++UI) {
2328     if (UI->getOpcode() != X86ISD::RET_FLAG)
2329       return false;
2330     // If we are returning more than one value, we can definitely
2331     // not make a tail call see PR19530
2332     if (UI->getNumOperands() > 4)
2333       return false;
2334     if (UI->getNumOperands() == 4 &&
2335         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2336       return false;
2337     HasRet = true;
2338   }
2339
2340   if (!HasRet)
2341     return false;
2342
2343   Chain = TCChain;
2344   return true;
2345 }
2346
2347 EVT
2348 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2349                                             ISD::NodeType ExtendKind) const {
2350   MVT ReturnMVT;
2351   // TODO: Is this also valid on 32-bit?
2352   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2353     ReturnMVT = MVT::i8;
2354   else
2355     ReturnMVT = MVT::i32;
2356
2357   EVT MinVT = getRegisterType(Context, ReturnMVT);
2358   return VT.bitsLT(MinVT) ? MinVT : VT;
2359 }
2360
2361 /// Lower the result values of a call into the
2362 /// appropriate copies out of appropriate physical registers.
2363 ///
2364 SDValue
2365 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2366                                    CallingConv::ID CallConv, bool isVarArg,
2367                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2368                                    SDLoc dl, SelectionDAG &DAG,
2369                                    SmallVectorImpl<SDValue> &InVals) const {
2370
2371   // Assign locations to each value returned by this call.
2372   SmallVector<CCValAssign, 16> RVLocs;
2373   bool Is64Bit = Subtarget->is64Bit();
2374   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2375                  *DAG.getContext());
2376   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2377
2378   // Copy all of the result registers out of their specified physreg.
2379   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2380     CCValAssign &VA = RVLocs[i];
2381     EVT CopyVT = VA.getLocVT();
2382
2383     // If this is x86-64, and we disabled SSE, we can't return FP values
2384     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2385         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2386       report_fatal_error("SSE register return with SSE disabled");
2387     }
2388
2389     // If we prefer to use the value in xmm registers, copy it out as f80 and
2390     // use a truncate to move it from fp stack reg to xmm reg.
2391     bool RoundAfterCopy = false;
2392     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2393         isScalarFPTypeInSSEReg(VA.getValVT())) {
2394       CopyVT = MVT::f80;
2395       RoundAfterCopy = (CopyVT != VA.getLocVT());
2396     }
2397
2398     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2399                                CopyVT, InFlag).getValue(1);
2400     SDValue Val = Chain.getValue(0);
2401
2402     if (RoundAfterCopy)
2403       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2404                         // This truncation won't change the value.
2405                         DAG.getIntPtrConstant(1, dl));
2406
2407     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2408       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2409
2410     InFlag = Chain.getValue(2);
2411     InVals.push_back(Val);
2412   }
2413
2414   return Chain;
2415 }
2416
2417 //===----------------------------------------------------------------------===//
2418 //                C & StdCall & Fast Calling Convention implementation
2419 //===----------------------------------------------------------------------===//
2420 //  StdCall calling convention seems to be standard for many Windows' API
2421 //  routines and around. It differs from C calling convention just a little:
2422 //  callee should clean up the stack, not caller. Symbols should be also
2423 //  decorated in some fancy way :) It doesn't support any vector arguments.
2424 //  For info on fast calling convention see Fast Calling Convention (tail call)
2425 //  implementation LowerX86_32FastCCCallTo.
2426
2427 /// CallIsStructReturn - Determines whether a call uses struct return
2428 /// semantics.
2429 enum StructReturnType {
2430   NotStructReturn,
2431   RegStructReturn,
2432   StackStructReturn
2433 };
2434 static StructReturnType
2435 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2436   if (Outs.empty())
2437     return NotStructReturn;
2438
2439   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2440   if (!Flags.isSRet())
2441     return NotStructReturn;
2442   if (Flags.isInReg())
2443     return RegStructReturn;
2444   return StackStructReturn;
2445 }
2446
2447 /// Determines whether a function uses struct return semantics.
2448 static StructReturnType
2449 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2450   if (Ins.empty())
2451     return NotStructReturn;
2452
2453   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2454   if (!Flags.isSRet())
2455     return NotStructReturn;
2456   if (Flags.isInReg())
2457     return RegStructReturn;
2458   return StackStructReturn;
2459 }
2460
2461 /// Make a copy of an aggregate at address specified by "Src" to address
2462 /// "Dst" with size and alignment information specified by the specific
2463 /// parameter attribute. The copy will be passed as a byval function parameter.
2464 static SDValue
2465 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2466                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2467                           SDLoc dl) {
2468   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2469
2470   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2471                        /*isVolatile*/false, /*AlwaysInline=*/true,
2472                        /*isTailCall*/false,
2473                        MachinePointerInfo(), MachinePointerInfo());
2474 }
2475
2476 /// Return true if the calling convention is one that we can guarantee TCO for.
2477 static bool canGuaranteeTCO(CallingConv::ID CC) {
2478   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2479           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2480 }
2481
2482 /// Return true if we might ever do TCO for calls with this calling convention.
2483 static bool mayTailCallThisCC(CallingConv::ID CC) {
2484   switch (CC) {
2485   // C calling conventions:
2486   case CallingConv::C:
2487   case CallingConv::X86_64_Win64:
2488   case CallingConv::X86_64_SysV:
2489   // Callee pop conventions:
2490   case CallingConv::X86_ThisCall:
2491   case CallingConv::X86_StdCall:
2492   case CallingConv::X86_VectorCall:
2493   case CallingConv::X86_FastCall:
2494     return true;
2495   default:
2496     return canGuaranteeTCO(CC);
2497   }
2498 }
2499
2500 /// Return true if the function is being made into a tailcall target by
2501 /// changing its ABI.
2502 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2503   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2504 }
2505
2506 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2507   auto Attr =
2508       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2509   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2510     return false;
2511
2512   CallSite CS(CI);
2513   CallingConv::ID CalleeCC = CS.getCallingConv();
2514   if (!mayTailCallThisCC(CalleeCC))
2515     return false;
2516
2517   return true;
2518 }
2519
2520 SDValue
2521 X86TargetLowering::LowerMemArgument(SDValue Chain,
2522                                     CallingConv::ID CallConv,
2523                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2524                                     SDLoc dl, SelectionDAG &DAG,
2525                                     const CCValAssign &VA,
2526                                     MachineFrameInfo *MFI,
2527                                     unsigned i) const {
2528   // Create the nodes corresponding to a load from this parameter slot.
2529   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2530   bool AlwaysUseMutable = shouldGuaranteeTCO(
2531       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2532   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2533   EVT ValVT;
2534
2535   // If value is passed by pointer we have address passed instead of the value
2536   // itself.
2537   bool ExtendedInMem = VA.isExtInLoc() &&
2538     VA.getValVT().getScalarType() == MVT::i1;
2539
2540   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2541     ValVT = VA.getLocVT();
2542   else
2543     ValVT = VA.getValVT();
2544
2545   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2546   // changed with more analysis.
2547   // In case of tail call optimization mark all arguments mutable. Since they
2548   // could be overwritten by lowering of arguments in case of a tail call.
2549   if (Flags.isByVal()) {
2550     unsigned Bytes = Flags.getByValSize();
2551     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2552     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2553     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2554   } else {
2555     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2556                                     VA.getLocMemOffset(), isImmutable);
2557     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2558     SDValue Val = DAG.getLoad(
2559         ValVT, dl, Chain, FIN,
2560         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2561         false, false, 0);
2562     return ExtendedInMem ?
2563       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2564   }
2565 }
2566
2567 // FIXME: Get this from tablegen.
2568 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2569                                                 const X86Subtarget *Subtarget) {
2570   assert(Subtarget->is64Bit());
2571
2572   if (Subtarget->isCallingConvWin64(CallConv)) {
2573     static const MCPhysReg GPR64ArgRegsWin64[] = {
2574       X86::RCX, X86::RDX, X86::R8,  X86::R9
2575     };
2576     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2577   }
2578
2579   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2580     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2581   };
2582   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2583 }
2584
2585 // FIXME: Get this from tablegen.
2586 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2587                                                 CallingConv::ID CallConv,
2588                                                 const X86Subtarget *Subtarget) {
2589   assert(Subtarget->is64Bit());
2590   if (Subtarget->isCallingConvWin64(CallConv)) {
2591     // The XMM registers which might contain var arg parameters are shadowed
2592     // in their paired GPR.  So we only need to save the GPR to their home
2593     // slots.
2594     // TODO: __vectorcall will change this.
2595     return None;
2596   }
2597
2598   const Function *Fn = MF.getFunction();
2599   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2600   bool isSoftFloat = Subtarget->useSoftFloat();
2601   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2602          "SSE register cannot be used when SSE is disabled!");
2603   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2604     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2605     // registers.
2606     return None;
2607
2608   static const MCPhysReg XMMArgRegs64Bit[] = {
2609     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2610     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2611   };
2612   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2613 }
2614
2615 SDValue X86TargetLowering::LowerFormalArguments(
2616     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2617     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2618     SmallVectorImpl<SDValue> &InVals) const {
2619   MachineFunction &MF = DAG.getMachineFunction();
2620   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2621   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2622
2623   const Function* Fn = MF.getFunction();
2624   if (Fn->hasExternalLinkage() &&
2625       Subtarget->isTargetCygMing() &&
2626       Fn->getName() == "main")
2627     FuncInfo->setForceFramePointer(true);
2628
2629   MachineFrameInfo *MFI = MF.getFrameInfo();
2630   bool Is64Bit = Subtarget->is64Bit();
2631   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2632
2633   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2634          "Var args not supported with calling convention fastcc, ghc or hipe");
2635
2636   // Assign locations to all of the incoming arguments.
2637   SmallVector<CCValAssign, 16> ArgLocs;
2638   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2639
2640   // Allocate shadow area for Win64
2641   if (IsWin64)
2642     CCInfo.AllocateStack(32, 8);
2643
2644   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2645
2646   unsigned LastVal = ~0U;
2647   SDValue ArgValue;
2648   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2649     CCValAssign &VA = ArgLocs[i];
2650     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2651     // places.
2652     assert(VA.getValNo() != LastVal &&
2653            "Don't support value assigned to multiple locs yet");
2654     (void)LastVal;
2655     LastVal = VA.getValNo();
2656
2657     if (VA.isRegLoc()) {
2658       EVT RegVT = VA.getLocVT();
2659       const TargetRegisterClass *RC;
2660       if (RegVT == MVT::i32)
2661         RC = &X86::GR32RegClass;
2662       else if (Is64Bit && RegVT == MVT::i64)
2663         RC = &X86::GR64RegClass;
2664       else if (RegVT == MVT::f32)
2665         RC = &X86::FR32RegClass;
2666       else if (RegVT == MVT::f64)
2667         RC = &X86::FR64RegClass;
2668       else if (RegVT.is512BitVector())
2669         RC = &X86::VR512RegClass;
2670       else if (RegVT.is256BitVector())
2671         RC = &X86::VR256RegClass;
2672       else if (RegVT.is128BitVector())
2673         RC = &X86::VR128RegClass;
2674       else if (RegVT == MVT::x86mmx)
2675         RC = &X86::VR64RegClass;
2676       else if (RegVT == MVT::i1)
2677         RC = &X86::VK1RegClass;
2678       else if (RegVT == MVT::v8i1)
2679         RC = &X86::VK8RegClass;
2680       else if (RegVT == MVT::v16i1)
2681         RC = &X86::VK16RegClass;
2682       else if (RegVT == MVT::v32i1)
2683         RC = &X86::VK32RegClass;
2684       else if (RegVT == MVT::v64i1)
2685         RC = &X86::VK64RegClass;
2686       else
2687         llvm_unreachable("Unknown argument type!");
2688
2689       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2690       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2691
2692       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2693       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2694       // right size.
2695       if (VA.getLocInfo() == CCValAssign::SExt)
2696         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2697                                DAG.getValueType(VA.getValVT()));
2698       else if (VA.getLocInfo() == CCValAssign::ZExt)
2699         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2700                                DAG.getValueType(VA.getValVT()));
2701       else if (VA.getLocInfo() == CCValAssign::BCvt)
2702         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2703
2704       if (VA.isExtInLoc()) {
2705         // Handle MMX values passed in XMM regs.
2706         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2707           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2708         else
2709           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2710       }
2711     } else {
2712       assert(VA.isMemLoc());
2713       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2714     }
2715
2716     // If value is passed via pointer - do a load.
2717     if (VA.getLocInfo() == CCValAssign::Indirect)
2718       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2719                              MachinePointerInfo(), false, false, false, 0);
2720
2721     InVals.push_back(ArgValue);
2722   }
2723
2724   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2725     // All x86 ABIs require that for returning structs by value we copy the
2726     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2727     // the argument into a virtual register so that we can access it from the
2728     // return points.
2729     if (Ins[i].Flags.isSRet()) {
2730       unsigned Reg = FuncInfo->getSRetReturnReg();
2731       if (!Reg) {
2732         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2733         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2734         FuncInfo->setSRetReturnReg(Reg);
2735       }
2736       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2737       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2738       break;
2739     }
2740   }
2741
2742   unsigned StackSize = CCInfo.getNextStackOffset();
2743   // Align stack specially for tail calls.
2744   if (shouldGuaranteeTCO(CallConv,
2745                          MF.getTarget().Options.GuaranteedTailCallOpt))
2746     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2747
2748   // If the function takes variable number of arguments, make a frame index for
2749   // the start of the first vararg value... for expansion of llvm.va_start. We
2750   // can skip this if there are no va_start calls.
2751   if (MFI->hasVAStart() &&
2752       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2753                    CallConv != CallingConv::X86_ThisCall))) {
2754     FuncInfo->setVarArgsFrameIndex(
2755         MFI->CreateFixedObject(1, StackSize, true));
2756   }
2757
2758   MachineModuleInfo &MMI = MF.getMMI();
2759
2760   // Figure out if XMM registers are in use.
2761   assert(!(Subtarget->useSoftFloat() &&
2762            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2763          "SSE register cannot be used when SSE is disabled!");
2764
2765   // 64-bit calling conventions support varargs and register parameters, so we
2766   // have to do extra work to spill them in the prologue.
2767   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2768     // Find the first unallocated argument registers.
2769     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2770     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2771     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2772     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2773     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2774            "SSE register cannot be used when SSE is disabled!");
2775
2776     // Gather all the live in physical registers.
2777     SmallVector<SDValue, 6> LiveGPRs;
2778     SmallVector<SDValue, 8> LiveXMMRegs;
2779     SDValue ALVal;
2780     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2781       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2782       LiveGPRs.push_back(
2783           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2784     }
2785     if (!ArgXMMs.empty()) {
2786       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2787       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2788       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2789         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2790         LiveXMMRegs.push_back(
2791             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2792       }
2793     }
2794
2795     if (IsWin64) {
2796       // Get to the caller-allocated home save location.  Add 8 to account
2797       // for the return address.
2798       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2799       FuncInfo->setRegSaveFrameIndex(
2800           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2801       // Fixup to set vararg frame on shadow area (4 x i64).
2802       if (NumIntRegs < 4)
2803         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2804     } else {
2805       // For X86-64, if there are vararg parameters that are passed via
2806       // registers, then we must store them to their spots on the stack so
2807       // they may be loaded by deferencing the result of va_next.
2808       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2809       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2810       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2811           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2812     }
2813
2814     // Store the integer parameter registers.
2815     SmallVector<SDValue, 8> MemOps;
2816     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2817                                       getPointerTy(DAG.getDataLayout()));
2818     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2819     for (SDValue Val : LiveGPRs) {
2820       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2821                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2822       SDValue Store =
2823           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2824                        MachinePointerInfo::getFixedStack(
2825                            DAG.getMachineFunction(),
2826                            FuncInfo->getRegSaveFrameIndex(), Offset),
2827                        false, false, 0);
2828       MemOps.push_back(Store);
2829       Offset += 8;
2830     }
2831
2832     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2833       // Now store the XMM (fp + vector) parameter registers.
2834       SmallVector<SDValue, 12> SaveXMMOps;
2835       SaveXMMOps.push_back(Chain);
2836       SaveXMMOps.push_back(ALVal);
2837       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2838                              FuncInfo->getRegSaveFrameIndex(), dl));
2839       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2840                              FuncInfo->getVarArgsFPOffset(), dl));
2841       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2842                         LiveXMMRegs.end());
2843       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2844                                    MVT::Other, SaveXMMOps));
2845     }
2846
2847     if (!MemOps.empty())
2848       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2849   }
2850
2851   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2852     // Find the largest legal vector type.
2853     MVT VecVT = MVT::Other;
2854     // FIXME: Only some x86_32 calling conventions support AVX512.
2855     if (Subtarget->hasAVX512() &&
2856         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2857                      CallConv == CallingConv::Intel_OCL_BI)))
2858       VecVT = MVT::v16f32;
2859     else if (Subtarget->hasAVX())
2860       VecVT = MVT::v8f32;
2861     else if (Subtarget->hasSSE2())
2862       VecVT = MVT::v4f32;
2863
2864     // We forward some GPRs and some vector types.
2865     SmallVector<MVT, 2> RegParmTypes;
2866     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2867     RegParmTypes.push_back(IntVT);
2868     if (VecVT != MVT::Other)
2869       RegParmTypes.push_back(VecVT);
2870
2871     // Compute the set of forwarded registers. The rest are scratch.
2872     SmallVectorImpl<ForwardedRegister> &Forwards =
2873         FuncInfo->getForwardedMustTailRegParms();
2874     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2875
2876     // Conservatively forward AL on x86_64, since it might be used for varargs.
2877     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2878       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2879       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2880     }
2881
2882     // Copy all forwards from physical to virtual registers.
2883     for (ForwardedRegister &F : Forwards) {
2884       // FIXME: Can we use a less constrained schedule?
2885       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2886       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2887       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2888     }
2889   }
2890
2891   // Some CCs need callee pop.
2892   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2893                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2894     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2895   } else {
2896     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2897     // If this is an sret function, the return should pop the hidden pointer.
2898     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2899         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2900         argsAreStructReturn(Ins) == StackStructReturn)
2901       FuncInfo->setBytesToPopOnReturn(4);
2902   }
2903
2904   if (!Is64Bit) {
2905     // RegSaveFrameIndex is X86-64 only.
2906     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2907     if (CallConv == CallingConv::X86_FastCall ||
2908         CallConv == CallingConv::X86_ThisCall)
2909       // fastcc functions can't have varargs.
2910       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2911   }
2912
2913   FuncInfo->setArgumentStackSize(StackSize);
2914
2915   if (MMI.hasWinEHFuncInfo(Fn)) {
2916     if (Is64Bit) {
2917       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2918       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2919       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2920       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2921       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2922                            MachinePointerInfo::getFixedStack(
2923                                DAG.getMachineFunction(), UnwindHelpFI),
2924                            /*isVolatile=*/true,
2925                            /*isNonTemporal=*/false, /*Alignment=*/0);
2926     } else {
2927       // Functions using Win32 EH are considered to have opaque SP adjustments
2928       // to force local variables to be addressed from the frame or base
2929       // pointers.
2930       MFI->setHasOpaqueSPAdjustment(true);
2931     }
2932   }
2933
2934   return Chain;
2935 }
2936
2937 SDValue
2938 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2939                                     SDValue StackPtr, SDValue Arg,
2940                                     SDLoc dl, SelectionDAG &DAG,
2941                                     const CCValAssign &VA,
2942                                     ISD::ArgFlagsTy Flags) const {
2943   unsigned LocMemOffset = VA.getLocMemOffset();
2944   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2945   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2946                        StackPtr, PtrOff);
2947   if (Flags.isByVal())
2948     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2949
2950   return DAG.getStore(
2951       Chain, dl, Arg, PtrOff,
2952       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2953       false, false, 0);
2954 }
2955
2956 /// Emit a load of return address if tail call
2957 /// optimization is performed and it is required.
2958 SDValue
2959 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2960                                            SDValue &OutRetAddr, SDValue Chain,
2961                                            bool IsTailCall, bool Is64Bit,
2962                                            int FPDiff, SDLoc dl) const {
2963   // Adjust the Return address stack slot.
2964   EVT VT = getPointerTy(DAG.getDataLayout());
2965   OutRetAddr = getReturnAddressFrameIndex(DAG);
2966
2967   // Load the "old" Return address.
2968   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2969                            false, false, false, 0);
2970   return SDValue(OutRetAddr.getNode(), 1);
2971 }
2972
2973 /// Emit a store of the return address if tail call
2974 /// optimization is performed and it is required (FPDiff!=0).
2975 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2976                                         SDValue Chain, SDValue RetAddrFrIdx,
2977                                         EVT PtrVT, unsigned SlotSize,
2978                                         int FPDiff, SDLoc dl) {
2979   // Store the return address to the appropriate stack slot.
2980   if (!FPDiff) return Chain;
2981   // Calculate the new stack slot for the return address.
2982   int NewReturnAddrFI =
2983     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2984                                          false);
2985   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2986   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2987                        MachinePointerInfo::getFixedStack(
2988                            DAG.getMachineFunction(), NewReturnAddrFI),
2989                        false, false, 0);
2990   return Chain;
2991 }
2992
2993 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2994 /// operation of specified width.
2995 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2996                        SDValue V2) {
2997   unsigned NumElems = VT.getVectorNumElements();
2998   SmallVector<int, 8> Mask;
2999   Mask.push_back(NumElems);
3000   for (unsigned i = 1; i != NumElems; ++i)
3001     Mask.push_back(i);
3002   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3003 }
3004
3005 SDValue
3006 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3007                              SmallVectorImpl<SDValue> &InVals) const {
3008   SelectionDAG &DAG                     = CLI.DAG;
3009   SDLoc &dl                             = CLI.DL;
3010   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3011   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3012   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3013   SDValue Chain                         = CLI.Chain;
3014   SDValue Callee                        = CLI.Callee;
3015   CallingConv::ID CallConv              = CLI.CallConv;
3016   bool &isTailCall                      = CLI.IsTailCall;
3017   bool isVarArg                         = CLI.IsVarArg;
3018
3019   MachineFunction &MF = DAG.getMachineFunction();
3020   bool Is64Bit        = Subtarget->is64Bit();
3021   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
3022   StructReturnType SR = callIsStructReturn(Outs);
3023   bool IsSibcall      = false;
3024   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3025   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3026
3027   if (Attr.getValueAsString() == "true")
3028     isTailCall = false;
3029
3030   if (Subtarget->isPICStyleGOT() &&
3031       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3032     // If we are using a GOT, disable tail calls to external symbols with
3033     // default visibility. Tail calling such a symbol requires using a GOT
3034     // relocation, which forces early binding of the symbol. This breaks code
3035     // that require lazy function symbol resolution. Using musttail or
3036     // GuaranteedTailCallOpt will override this.
3037     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3038     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3039                G->getGlobal()->hasDefaultVisibility()))
3040       isTailCall = false;
3041   }
3042
3043   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3044   if (IsMustTail) {
3045     // Force this to be a tail call.  The verifier rules are enough to ensure
3046     // that we can lower this successfully without moving the return address
3047     // around.
3048     isTailCall = true;
3049   } else if (isTailCall) {
3050     // Check if it's really possible to do a tail call.
3051     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3052                     isVarArg, SR != NotStructReturn,
3053                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3054                     Outs, OutVals, Ins, DAG);
3055
3056     // Sibcalls are automatically detected tailcalls which do not require
3057     // ABI changes.
3058     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3059       IsSibcall = true;
3060
3061     if (isTailCall)
3062       ++NumTailCalls;
3063   }
3064
3065   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3066          "Var args not supported with calling convention fastcc, ghc or hipe");
3067
3068   // Analyze operands of the call, assigning locations to each operand.
3069   SmallVector<CCValAssign, 16> ArgLocs;
3070   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3071
3072   // Allocate shadow area for Win64
3073   if (IsWin64)
3074     CCInfo.AllocateStack(32, 8);
3075
3076   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3077
3078   // Get a count of how many bytes are to be pushed on the stack.
3079   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3080   if (IsSibcall)
3081     // This is a sibcall. The memory operands are available in caller's
3082     // own caller's stack.
3083     NumBytes = 0;
3084   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3085            canGuaranteeTCO(CallConv))
3086     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3087
3088   int FPDiff = 0;
3089   if (isTailCall && !IsSibcall && !IsMustTail) {
3090     // Lower arguments at fp - stackoffset + fpdiff.
3091     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3092
3093     FPDiff = NumBytesCallerPushed - NumBytes;
3094
3095     // Set the delta of movement of the returnaddr stackslot.
3096     // But only set if delta is greater than previous delta.
3097     if (FPDiff < X86Info->getTCReturnAddrDelta())
3098       X86Info->setTCReturnAddrDelta(FPDiff);
3099   }
3100
3101   unsigned NumBytesToPush = NumBytes;
3102   unsigned NumBytesToPop = NumBytes;
3103
3104   // If we have an inalloca argument, all stack space has already been allocated
3105   // for us and be right at the top of the stack.  We don't support multiple
3106   // arguments passed in memory when using inalloca.
3107   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3108     NumBytesToPush = 0;
3109     if (!ArgLocs.back().isMemLoc())
3110       report_fatal_error("cannot use inalloca attribute on a register "
3111                          "parameter");
3112     if (ArgLocs.back().getLocMemOffset() != 0)
3113       report_fatal_error("any parameter with the inalloca attribute must be "
3114                          "the only memory argument");
3115   }
3116
3117   if (!IsSibcall)
3118     Chain = DAG.getCALLSEQ_START(
3119         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3120
3121   SDValue RetAddrFrIdx;
3122   // Load return address for tail calls.
3123   if (isTailCall && FPDiff)
3124     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3125                                     Is64Bit, FPDiff, dl);
3126
3127   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3128   SmallVector<SDValue, 8> MemOpChains;
3129   SDValue StackPtr;
3130
3131   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3132   // of tail call optimization arguments are handle later.
3133   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3134   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3135     // Skip inalloca arguments, they have already been written.
3136     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3137     if (Flags.isInAlloca())
3138       continue;
3139
3140     CCValAssign &VA = ArgLocs[i];
3141     EVT RegVT = VA.getLocVT();
3142     SDValue Arg = OutVals[i];
3143     bool isByVal = Flags.isByVal();
3144
3145     // Promote the value if needed.
3146     switch (VA.getLocInfo()) {
3147     default: llvm_unreachable("Unknown loc info!");
3148     case CCValAssign::Full: break;
3149     case CCValAssign::SExt:
3150       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3151       break;
3152     case CCValAssign::ZExt:
3153       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3154       break;
3155     case CCValAssign::AExt:
3156       if (Arg.getValueType().isVector() &&
3157           Arg.getValueType().getScalarType() == MVT::i1)
3158         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3159       else if (RegVT.is128BitVector()) {
3160         // Special case: passing MMX values in XMM registers.
3161         Arg = DAG.getBitcast(MVT::i64, Arg);
3162         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3163         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3164       } else
3165         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3166       break;
3167     case CCValAssign::BCvt:
3168       Arg = DAG.getBitcast(RegVT, Arg);
3169       break;
3170     case CCValAssign::Indirect: {
3171       // Store the argument.
3172       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3173       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3174       Chain = DAG.getStore(
3175           Chain, dl, Arg, SpillSlot,
3176           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3177           false, false, 0);
3178       Arg = SpillSlot;
3179       break;
3180     }
3181     }
3182
3183     if (VA.isRegLoc()) {
3184       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3185       if (isVarArg && IsWin64) {
3186         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3187         // shadow reg if callee is a varargs function.
3188         unsigned ShadowReg = 0;
3189         switch (VA.getLocReg()) {
3190         case X86::XMM0: ShadowReg = X86::RCX; break;
3191         case X86::XMM1: ShadowReg = X86::RDX; break;
3192         case X86::XMM2: ShadowReg = X86::R8; break;
3193         case X86::XMM3: ShadowReg = X86::R9; break;
3194         }
3195         if (ShadowReg)
3196           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3197       }
3198     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3199       assert(VA.isMemLoc());
3200       if (!StackPtr.getNode())
3201         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3202                                       getPointerTy(DAG.getDataLayout()));
3203       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3204                                              dl, DAG, VA, Flags));
3205     }
3206   }
3207
3208   if (!MemOpChains.empty())
3209     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3210
3211   if (Subtarget->isPICStyleGOT()) {
3212     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3213     // GOT pointer.
3214     if (!isTailCall) {
3215       RegsToPass.push_back(std::make_pair(
3216           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3217                                           getPointerTy(DAG.getDataLayout()))));
3218     } else {
3219       // If we are tail calling and generating PIC/GOT style code load the
3220       // address of the callee into ECX. The value in ecx is used as target of
3221       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3222       // for tail calls on PIC/GOT architectures. Normally we would just put the
3223       // address of GOT into ebx and then call target@PLT. But for tail calls
3224       // ebx would be restored (since ebx is callee saved) before jumping to the
3225       // target@PLT.
3226
3227       // Note: The actual moving to ECX is done further down.
3228       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3229       if (G && !G->getGlobal()->hasLocalLinkage() &&
3230           G->getGlobal()->hasDefaultVisibility())
3231         Callee = LowerGlobalAddress(Callee, DAG);
3232       else if (isa<ExternalSymbolSDNode>(Callee))
3233         Callee = LowerExternalSymbol(Callee, DAG);
3234     }
3235   }
3236
3237   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3238     // From AMD64 ABI document:
3239     // For calls that may call functions that use varargs or stdargs
3240     // (prototype-less calls or calls to functions containing ellipsis (...) in
3241     // the declaration) %al is used as hidden argument to specify the number
3242     // of SSE registers used. The contents of %al do not need to match exactly
3243     // the number of registers, but must be an ubound on the number of SSE
3244     // registers used and is in the range 0 - 8 inclusive.
3245
3246     // Count the number of XMM registers allocated.
3247     static const MCPhysReg XMMArgRegs[] = {
3248       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3249       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3250     };
3251     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3252     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3253            && "SSE registers cannot be used when SSE is disabled");
3254
3255     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3256                                         DAG.getConstant(NumXMMRegs, dl,
3257                                                         MVT::i8)));
3258   }
3259
3260   if (isVarArg && IsMustTail) {
3261     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3262     for (const auto &F : Forwards) {
3263       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3264       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3265     }
3266   }
3267
3268   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3269   // don't need this because the eligibility check rejects calls that require
3270   // shuffling arguments passed in memory.
3271   if (!IsSibcall && isTailCall) {
3272     // Force all the incoming stack arguments to be loaded from the stack
3273     // before any new outgoing arguments are stored to the stack, because the
3274     // outgoing stack slots may alias the incoming argument stack slots, and
3275     // the alias isn't otherwise explicit. This is slightly more conservative
3276     // than necessary, because it means that each store effectively depends
3277     // on every argument instead of just those arguments it would clobber.
3278     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3279
3280     SmallVector<SDValue, 8> MemOpChains2;
3281     SDValue FIN;
3282     int FI = 0;
3283     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3284       CCValAssign &VA = ArgLocs[i];
3285       if (VA.isRegLoc())
3286         continue;
3287       assert(VA.isMemLoc());
3288       SDValue Arg = OutVals[i];
3289       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3290       // Skip inalloca arguments.  They don't require any work.
3291       if (Flags.isInAlloca())
3292         continue;
3293       // Create frame index.
3294       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3295       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3296       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3297       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3298
3299       if (Flags.isByVal()) {
3300         // Copy relative to framepointer.
3301         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3302         if (!StackPtr.getNode())
3303           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3304                                         getPointerTy(DAG.getDataLayout()));
3305         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3306                              StackPtr, Source);
3307
3308         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3309                                                          ArgChain,
3310                                                          Flags, DAG, dl));
3311       } else {
3312         // Store relative to framepointer.
3313         MemOpChains2.push_back(DAG.getStore(
3314             ArgChain, dl, Arg, FIN,
3315             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3316             false, false, 0));
3317       }
3318     }
3319
3320     if (!MemOpChains2.empty())
3321       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3322
3323     // Store the return address to the appropriate stack slot.
3324     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3325                                      getPointerTy(DAG.getDataLayout()),
3326                                      RegInfo->getSlotSize(), FPDiff, dl);
3327   }
3328
3329   // Build a sequence of copy-to-reg nodes chained together with token chain
3330   // and flag operands which copy the outgoing args into registers.
3331   SDValue InFlag;
3332   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3333     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3334                              RegsToPass[i].second, InFlag);
3335     InFlag = Chain.getValue(1);
3336   }
3337
3338   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3339     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3340     // In the 64-bit large code model, we have to make all calls
3341     // through a register, since the call instruction's 32-bit
3342     // pc-relative offset may not be large enough to hold the whole
3343     // address.
3344   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3345     // If the callee is a GlobalAddress node (quite common, every direct call
3346     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3347     // it.
3348     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3349
3350     // We should use extra load for direct calls to dllimported functions in
3351     // non-JIT mode.
3352     const GlobalValue *GV = G->getGlobal();
3353     if (!GV->hasDLLImportStorageClass()) {
3354       unsigned char OpFlags = 0;
3355       bool ExtraLoad = false;
3356       unsigned WrapperKind = ISD::DELETED_NODE;
3357
3358       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3359       // external symbols most go through the PLT in PIC mode.  If the symbol
3360       // has hidden or protected visibility, or if it is static or local, then
3361       // we don't need to use the PLT - we can directly call it.
3362       if (Subtarget->isTargetELF() &&
3363           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3364           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3365         OpFlags = X86II::MO_PLT;
3366       } else if (Subtarget->isPICStyleStubAny() &&
3367                  !GV->isStrongDefinitionForLinker() &&
3368                  (!Subtarget->getTargetTriple().isMacOSX() ||
3369                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3370         // PC-relative references to external symbols should go through $stub,
3371         // unless we're building with the leopard linker or later, which
3372         // automatically synthesizes these stubs.
3373         OpFlags = X86II::MO_DARWIN_STUB;
3374       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3375                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3376         // If the function is marked as non-lazy, generate an indirect call
3377         // which loads from the GOT directly. This avoids runtime overhead
3378         // at the cost of eager binding (and one extra byte of encoding).
3379         OpFlags = X86II::MO_GOTPCREL;
3380         WrapperKind = X86ISD::WrapperRIP;
3381         ExtraLoad = true;
3382       }
3383
3384       Callee = DAG.getTargetGlobalAddress(
3385           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3386
3387       // Add a wrapper if needed.
3388       if (WrapperKind != ISD::DELETED_NODE)
3389         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3390                              getPointerTy(DAG.getDataLayout()), Callee);
3391       // Add extra indirection if needed.
3392       if (ExtraLoad)
3393         Callee = DAG.getLoad(
3394             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3395             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3396             false, 0);
3397     }
3398   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3399     unsigned char OpFlags = 0;
3400
3401     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3402     // external symbols should go through the PLT.
3403     if (Subtarget->isTargetELF() &&
3404         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3405       OpFlags = X86II::MO_PLT;
3406     } else if (Subtarget->isPICStyleStubAny() &&
3407                (!Subtarget->getTargetTriple().isMacOSX() ||
3408                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3409       // PC-relative references to external symbols should go through $stub,
3410       // unless we're building with the leopard linker or later, which
3411       // automatically synthesizes these stubs.
3412       OpFlags = X86II::MO_DARWIN_STUB;
3413     }
3414
3415     Callee = DAG.getTargetExternalSymbol(
3416         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3417   } else if (Subtarget->isTarget64BitILP32() &&
3418              Callee->getValueType(0) == MVT::i32) {
3419     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3420     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3421   }
3422
3423   // Returns a chain & a flag for retval copy to use.
3424   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3425   SmallVector<SDValue, 8> Ops;
3426
3427   if (!IsSibcall && isTailCall) {
3428     Chain = DAG.getCALLSEQ_END(Chain,
3429                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3430                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3431     InFlag = Chain.getValue(1);
3432   }
3433
3434   Ops.push_back(Chain);
3435   Ops.push_back(Callee);
3436
3437   if (isTailCall)
3438     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3439
3440   // Add argument registers to the end of the list so that they are known live
3441   // into the call.
3442   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3443     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3444                                   RegsToPass[i].second.getValueType()));
3445
3446   // Add a register mask operand representing the call-preserved registers.
3447   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3448   assert(Mask && "Missing call preserved mask for calling convention");
3449
3450   // If this is an invoke in a 32-bit function using a funclet-based
3451   // personality, assume the function clobbers all registers. If an exception
3452   // is thrown, the runtime will not restore CSRs.
3453   // FIXME: Model this more precisely so that we can register allocate across
3454   // the normal edge and spill and fill across the exceptional edge.
3455   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3456     const Function *CallerFn = MF.getFunction();
3457     EHPersonality Pers =
3458         CallerFn->hasPersonalityFn()
3459             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3460             : EHPersonality::Unknown;
3461     if (isFuncletEHPersonality(Pers))
3462       Mask = RegInfo->getNoPreservedMask();
3463   }
3464
3465   Ops.push_back(DAG.getRegisterMask(Mask));
3466
3467   if (InFlag.getNode())
3468     Ops.push_back(InFlag);
3469
3470   if (isTailCall) {
3471     // We used to do:
3472     //// If this is the first return lowered for this function, add the regs
3473     //// to the liveout set for the function.
3474     // This isn't right, although it's probably harmless on x86; liveouts
3475     // should be computed from returns not tail calls.  Consider a void
3476     // function making a tail call to a function returning int.
3477     MF.getFrameInfo()->setHasTailCall();
3478     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3479   }
3480
3481   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3482   InFlag = Chain.getValue(1);
3483
3484   // Create the CALLSEQ_END node.
3485   unsigned NumBytesForCalleeToPop;
3486   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3487                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3488     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3489   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3490            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3491            SR == StackStructReturn)
3492     // If this is a call to a struct-return function, the callee
3493     // pops the hidden struct pointer, so we have to push it back.
3494     // This is common for Darwin/X86, Linux & Mingw32 targets.
3495     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3496     NumBytesForCalleeToPop = 4;
3497   else
3498     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3499
3500   // Returns a flag for retval copy to use.
3501   if (!IsSibcall) {
3502     Chain = DAG.getCALLSEQ_END(Chain,
3503                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3504                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3505                                                      true),
3506                                InFlag, dl);
3507     InFlag = Chain.getValue(1);
3508   }
3509
3510   // Handle result values, copying them out of physregs into vregs that we
3511   // return.
3512   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3513                          Ins, dl, DAG, InVals);
3514 }
3515
3516 //===----------------------------------------------------------------------===//
3517 //                Fast Calling Convention (tail call) implementation
3518 //===----------------------------------------------------------------------===//
3519
3520 //  Like std call, callee cleans arguments, convention except that ECX is
3521 //  reserved for storing the tail called function address. Only 2 registers are
3522 //  free for argument passing (inreg). Tail call optimization is performed
3523 //  provided:
3524 //                * tailcallopt is enabled
3525 //                * caller/callee are fastcc
3526 //  On X86_64 architecture with GOT-style position independent code only local
3527 //  (within module) calls are supported at the moment.
3528 //  To keep the stack aligned according to platform abi the function
3529 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3530 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3531 //  If a tail called function callee has more arguments than the caller the
3532 //  caller needs to make sure that there is room to move the RETADDR to. This is
3533 //  achieved by reserving an area the size of the argument delta right after the
3534 //  original RETADDR, but before the saved framepointer or the spilled registers
3535 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3536 //  stack layout:
3537 //    arg1
3538 //    arg2
3539 //    RETADDR
3540 //    [ new RETADDR
3541 //      move area ]
3542 //    (possible EBP)
3543 //    ESI
3544 //    EDI
3545 //    local1 ..
3546
3547 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3548 /// requirement.
3549 unsigned
3550 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3551                                                SelectionDAG& DAG) const {
3552   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3553   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3554   unsigned StackAlignment = TFI.getStackAlignment();
3555   uint64_t AlignMask = StackAlignment - 1;
3556   int64_t Offset = StackSize;
3557   unsigned SlotSize = RegInfo->getSlotSize();
3558   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3559     // Number smaller than 12 so just add the difference.
3560     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3561   } else {
3562     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3563     Offset = ((~AlignMask) & Offset) + StackAlignment +
3564       (StackAlignment-SlotSize);
3565   }
3566   return Offset;
3567 }
3568
3569 /// Return true if the given stack call argument is already available in the
3570 /// same position (relatively) of the caller's incoming argument stack.
3571 static
3572 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3573                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3574                          const X86InstrInfo *TII) {
3575   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3576   int FI = INT_MAX;
3577   if (Arg.getOpcode() == ISD::CopyFromReg) {
3578     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3579     if (!TargetRegisterInfo::isVirtualRegister(VR))
3580       return false;
3581     MachineInstr *Def = MRI->getVRegDef(VR);
3582     if (!Def)
3583       return false;
3584     if (!Flags.isByVal()) {
3585       if (!TII->isLoadFromStackSlot(Def, FI))
3586         return false;
3587     } else {
3588       unsigned Opcode = Def->getOpcode();
3589       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3590            Opcode == X86::LEA64_32r) &&
3591           Def->getOperand(1).isFI()) {
3592         FI = Def->getOperand(1).getIndex();
3593         Bytes = Flags.getByValSize();
3594       } else
3595         return false;
3596     }
3597   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3598     if (Flags.isByVal())
3599       // ByVal argument is passed in as a pointer but it's now being
3600       // dereferenced. e.g.
3601       // define @foo(%struct.X* %A) {
3602       //   tail call @bar(%struct.X* byval %A)
3603       // }
3604       return false;
3605     SDValue Ptr = Ld->getBasePtr();
3606     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3607     if (!FINode)
3608       return false;
3609     FI = FINode->getIndex();
3610   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3611     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3612     FI = FINode->getIndex();
3613     Bytes = Flags.getByValSize();
3614   } else
3615     return false;
3616
3617   assert(FI != INT_MAX);
3618   if (!MFI->isFixedObjectIndex(FI))
3619     return false;
3620   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3621 }
3622
3623 /// Check whether the call is eligible for tail call optimization. Targets
3624 /// that want to do tail call optimization should implement this function.
3625 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3626     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3627     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3628     const SmallVectorImpl<ISD::OutputArg> &Outs,
3629     const SmallVectorImpl<SDValue> &OutVals,
3630     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3631   if (!mayTailCallThisCC(CalleeCC))
3632     return false;
3633
3634   // If -tailcallopt is specified, make fastcc functions tail-callable.
3635   MachineFunction &MF = DAG.getMachineFunction();
3636   const Function *CallerF = MF.getFunction();
3637
3638   // If the function return type is x86_fp80 and the callee return type is not,
3639   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3640   // perform a tailcall optimization here.
3641   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3642     return false;
3643
3644   CallingConv::ID CallerCC = CallerF->getCallingConv();
3645   bool CCMatch = CallerCC == CalleeCC;
3646   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3647   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3648
3649   // Win64 functions have extra shadow space for argument homing. Don't do the
3650   // sibcall if the caller and callee have mismatched expectations for this
3651   // space.
3652   if (IsCalleeWin64 != IsCallerWin64)
3653     return false;
3654
3655   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3656     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3657       return true;
3658     return false;
3659   }
3660
3661   // Look for obvious safe cases to perform tail call optimization that do not
3662   // require ABI changes. This is what gcc calls sibcall.
3663
3664   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3665   // emit a special epilogue.
3666   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3667   if (RegInfo->needsStackRealignment(MF))
3668     return false;
3669
3670   // Also avoid sibcall optimization if either caller or callee uses struct
3671   // return semantics.
3672   if (isCalleeStructRet || isCallerStructRet)
3673     return false;
3674
3675   // Do not sibcall optimize vararg calls unless all arguments are passed via
3676   // registers.
3677   if (isVarArg && !Outs.empty()) {
3678     // Optimizing for varargs on Win64 is unlikely to be safe without
3679     // additional testing.
3680     if (IsCalleeWin64 || IsCallerWin64)
3681       return false;
3682
3683     SmallVector<CCValAssign, 16> ArgLocs;
3684     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3685                    *DAG.getContext());
3686
3687     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3688     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3689       if (!ArgLocs[i].isRegLoc())
3690         return false;
3691   }
3692
3693   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3694   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3695   // this into a sibcall.
3696   bool Unused = false;
3697   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3698     if (!Ins[i].Used) {
3699       Unused = true;
3700       break;
3701     }
3702   }
3703   if (Unused) {
3704     SmallVector<CCValAssign, 16> RVLocs;
3705     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3706                    *DAG.getContext());
3707     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3708     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3709       CCValAssign &VA = RVLocs[i];
3710       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3711         return false;
3712     }
3713   }
3714
3715   // If the calling conventions do not match, then we'd better make sure the
3716   // results are returned in the same way as what the caller expects.
3717   if (!CCMatch) {
3718     SmallVector<CCValAssign, 16> RVLocs1;
3719     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3720                     *DAG.getContext());
3721     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3722
3723     SmallVector<CCValAssign, 16> RVLocs2;
3724     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3725                     *DAG.getContext());
3726     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3727
3728     if (RVLocs1.size() != RVLocs2.size())
3729       return false;
3730     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3731       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3732         return false;
3733       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3734         return false;
3735       if (RVLocs1[i].isRegLoc()) {
3736         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3737           return false;
3738       } else {
3739         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3740           return false;
3741       }
3742     }
3743   }
3744
3745   unsigned StackArgsSize = 0;
3746
3747   // If the callee takes no arguments then go on to check the results of the
3748   // call.
3749   if (!Outs.empty()) {
3750     // Check if stack adjustment is needed. For now, do not do this if any
3751     // argument is passed on the stack.
3752     SmallVector<CCValAssign, 16> ArgLocs;
3753     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3754                    *DAG.getContext());
3755
3756     // Allocate shadow area for Win64
3757     if (IsCalleeWin64)
3758       CCInfo.AllocateStack(32, 8);
3759
3760     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3761     StackArgsSize = CCInfo.getNextStackOffset();
3762
3763     if (CCInfo.getNextStackOffset()) {
3764       // Check if the arguments are already laid out in the right way as
3765       // the caller's fixed stack objects.
3766       MachineFrameInfo *MFI = MF.getFrameInfo();
3767       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3768       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3769       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3770         CCValAssign &VA = ArgLocs[i];
3771         SDValue Arg = OutVals[i];
3772         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3773         if (VA.getLocInfo() == CCValAssign::Indirect)
3774           return false;
3775         if (!VA.isRegLoc()) {
3776           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3777                                    MFI, MRI, TII))
3778             return false;
3779         }
3780       }
3781     }
3782
3783     // If the tailcall address may be in a register, then make sure it's
3784     // possible to register allocate for it. In 32-bit, the call address can
3785     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3786     // callee-saved registers are restored. These happen to be the same
3787     // registers used to pass 'inreg' arguments so watch out for those.
3788     if (!Subtarget->is64Bit() &&
3789         ((!isa<GlobalAddressSDNode>(Callee) &&
3790           !isa<ExternalSymbolSDNode>(Callee)) ||
3791          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3792       unsigned NumInRegs = 0;
3793       // In PIC we need an extra register to formulate the address computation
3794       // for the callee.
3795       unsigned MaxInRegs =
3796         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3797
3798       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3799         CCValAssign &VA = ArgLocs[i];
3800         if (!VA.isRegLoc())
3801           continue;
3802         unsigned Reg = VA.getLocReg();
3803         switch (Reg) {
3804         default: break;
3805         case X86::EAX: case X86::EDX: case X86::ECX:
3806           if (++NumInRegs == MaxInRegs)
3807             return false;
3808           break;
3809         }
3810       }
3811     }
3812   }
3813
3814   bool CalleeWillPop =
3815       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3816                        MF.getTarget().Options.GuaranteedTailCallOpt);
3817
3818   if (unsigned BytesToPop =
3819           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3820     // If we have bytes to pop, the callee must pop them.
3821     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3822     if (!CalleePopMatches)
3823       return false;
3824   } else if (CalleeWillPop && StackArgsSize > 0) {
3825     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3826     return false;
3827   }
3828
3829   return true;
3830 }
3831
3832 FastISel *
3833 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3834                                   const TargetLibraryInfo *libInfo) const {
3835   return X86::createFastISel(funcInfo, libInfo);
3836 }
3837
3838 //===----------------------------------------------------------------------===//
3839 //                           Other Lowering Hooks
3840 //===----------------------------------------------------------------------===//
3841
3842 static bool MayFoldLoad(SDValue Op) {
3843   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3844 }
3845
3846 static bool MayFoldIntoStore(SDValue Op) {
3847   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3848 }
3849
3850 static bool isTargetShuffle(unsigned Opcode) {
3851   switch(Opcode) {
3852   default: return false;
3853   case X86ISD::BLENDI:
3854   case X86ISD::PSHUFB:
3855   case X86ISD::PSHUFD:
3856   case X86ISD::PSHUFHW:
3857   case X86ISD::PSHUFLW:
3858   case X86ISD::SHUFP:
3859   case X86ISD::PALIGNR:
3860   case X86ISD::MOVLHPS:
3861   case X86ISD::MOVLHPD:
3862   case X86ISD::MOVHLPS:
3863   case X86ISD::MOVLPS:
3864   case X86ISD::MOVLPD:
3865   case X86ISD::MOVSHDUP:
3866   case X86ISD::MOVSLDUP:
3867   case X86ISD::MOVDDUP:
3868   case X86ISD::MOVSS:
3869   case X86ISD::MOVSD:
3870   case X86ISD::UNPCKL:
3871   case X86ISD::UNPCKH:
3872   case X86ISD::VPERMILPI:
3873   case X86ISD::VPERM2X128:
3874   case X86ISD::VPERMI:
3875   case X86ISD::VPERMV:
3876   case X86ISD::VPERMV3:
3877     return true;
3878   }
3879 }
3880
3881 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3882                                     SDValue V1, unsigned TargetMask,
3883                                     SelectionDAG &DAG) {
3884   switch(Opc) {
3885   default: llvm_unreachable("Unknown x86 shuffle node");
3886   case X86ISD::PSHUFD:
3887   case X86ISD::PSHUFHW:
3888   case X86ISD::PSHUFLW:
3889   case X86ISD::VPERMILPI:
3890   case X86ISD::VPERMI:
3891     return DAG.getNode(Opc, dl, VT, V1,
3892                        DAG.getConstant(TargetMask, dl, MVT::i8));
3893   }
3894 }
3895
3896 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3897                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3898   switch(Opc) {
3899   default: llvm_unreachable("Unknown x86 shuffle node");
3900   case X86ISD::MOVLHPS:
3901   case X86ISD::MOVLHPD:
3902   case X86ISD::MOVHLPS:
3903   case X86ISD::MOVLPS:
3904   case X86ISD::MOVLPD:
3905   case X86ISD::MOVSS:
3906   case X86ISD::MOVSD:
3907   case X86ISD::UNPCKL:
3908   case X86ISD::UNPCKH:
3909     return DAG.getNode(Opc, dl, VT, V1, V2);
3910   }
3911 }
3912
3913 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3914   MachineFunction &MF = DAG.getMachineFunction();
3915   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3916   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3917   int ReturnAddrIndex = FuncInfo->getRAIndex();
3918
3919   if (ReturnAddrIndex == 0) {
3920     // Set up a frame object for the return address.
3921     unsigned SlotSize = RegInfo->getSlotSize();
3922     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3923                                                            -(int64_t)SlotSize,
3924                                                            false);
3925     FuncInfo->setRAIndex(ReturnAddrIndex);
3926   }
3927
3928   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3929 }
3930
3931 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3932                                        bool hasSymbolicDisplacement) {
3933   // Offset should fit into 32 bit immediate field.
3934   if (!isInt<32>(Offset))
3935     return false;
3936
3937   // If we don't have a symbolic displacement - we don't have any extra
3938   // restrictions.
3939   if (!hasSymbolicDisplacement)
3940     return true;
3941
3942   // FIXME: Some tweaks might be needed for medium code model.
3943   if (M != CodeModel::Small && M != CodeModel::Kernel)
3944     return false;
3945
3946   // For small code model we assume that latest object is 16MB before end of 31
3947   // bits boundary. We may also accept pretty large negative constants knowing
3948   // that all objects are in the positive half of address space.
3949   if (M == CodeModel::Small && Offset < 16*1024*1024)
3950     return true;
3951
3952   // For kernel code model we know that all object resist in the negative half
3953   // of 32bits address space. We may not accept negative offsets, since they may
3954   // be just off and we may accept pretty large positive ones.
3955   if (M == CodeModel::Kernel && Offset >= 0)
3956     return true;
3957
3958   return false;
3959 }
3960
3961 /// Determines whether the callee is required to pop its own arguments.
3962 /// Callee pop is necessary to support tail calls.
3963 bool X86::isCalleePop(CallingConv::ID CallingConv,
3964                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3965   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3966   // can guarantee TCO.
3967   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3968     return true;
3969
3970   switch (CallingConv) {
3971   default:
3972     return false;
3973   case CallingConv::X86_StdCall:
3974   case CallingConv::X86_FastCall:
3975   case CallingConv::X86_ThisCall:
3976   case CallingConv::X86_VectorCall:
3977     return !is64Bit;
3978   }
3979 }
3980
3981 /// \brief Return true if the condition is an unsigned comparison operation.
3982 static bool isX86CCUnsigned(unsigned X86CC) {
3983   switch (X86CC) {
3984   default: llvm_unreachable("Invalid integer condition!");
3985   case X86::COND_E:     return true;
3986   case X86::COND_G:     return false;
3987   case X86::COND_GE:    return false;
3988   case X86::COND_L:     return false;
3989   case X86::COND_LE:    return false;
3990   case X86::COND_NE:    return true;
3991   case X86::COND_B:     return true;
3992   case X86::COND_A:     return true;
3993   case X86::COND_BE:    return true;
3994   case X86::COND_AE:    return true;
3995   }
3996   llvm_unreachable("covered switch fell through?!");
3997 }
3998
3999 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4000 /// condition code, returning the condition code and the LHS/RHS of the
4001 /// comparison to make.
4002 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4003                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4004   if (!isFP) {
4005     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4006       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4007         // X > -1   -> X == 0, jump !sign.
4008         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4009         return X86::COND_NS;
4010       }
4011       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4012         // X < 0   -> X == 0, jump on sign.
4013         return X86::COND_S;
4014       }
4015       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4016         // X < 1   -> X <= 0
4017         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4018         return X86::COND_LE;
4019       }
4020     }
4021
4022     switch (SetCCOpcode) {
4023     default: llvm_unreachable("Invalid integer condition!");
4024     case ISD::SETEQ:  return X86::COND_E;
4025     case ISD::SETGT:  return X86::COND_G;
4026     case ISD::SETGE:  return X86::COND_GE;
4027     case ISD::SETLT:  return X86::COND_L;
4028     case ISD::SETLE:  return X86::COND_LE;
4029     case ISD::SETNE:  return X86::COND_NE;
4030     case ISD::SETULT: return X86::COND_B;
4031     case ISD::SETUGT: return X86::COND_A;
4032     case ISD::SETULE: return X86::COND_BE;
4033     case ISD::SETUGE: return X86::COND_AE;
4034     }
4035   }
4036
4037   // First determine if it is required or is profitable to flip the operands.
4038
4039   // If LHS is a foldable load, but RHS is not, flip the condition.
4040   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4041       !ISD::isNON_EXTLoad(RHS.getNode())) {
4042     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4043     std::swap(LHS, RHS);
4044   }
4045
4046   switch (SetCCOpcode) {
4047   default: break;
4048   case ISD::SETOLT:
4049   case ISD::SETOLE:
4050   case ISD::SETUGT:
4051   case ISD::SETUGE:
4052     std::swap(LHS, RHS);
4053     break;
4054   }
4055
4056   // On a floating point condition, the flags are set as follows:
4057   // ZF  PF  CF   op
4058   //  0 | 0 | 0 | X > Y
4059   //  0 | 0 | 1 | X < Y
4060   //  1 | 0 | 0 | X == Y
4061   //  1 | 1 | 1 | unordered
4062   switch (SetCCOpcode) {
4063   default: llvm_unreachable("Condcode should be pre-legalized away");
4064   case ISD::SETUEQ:
4065   case ISD::SETEQ:   return X86::COND_E;
4066   case ISD::SETOLT:              // flipped
4067   case ISD::SETOGT:
4068   case ISD::SETGT:   return X86::COND_A;
4069   case ISD::SETOLE:              // flipped
4070   case ISD::SETOGE:
4071   case ISD::SETGE:   return X86::COND_AE;
4072   case ISD::SETUGT:              // flipped
4073   case ISD::SETULT:
4074   case ISD::SETLT:   return X86::COND_B;
4075   case ISD::SETUGE:              // flipped
4076   case ISD::SETULE:
4077   case ISD::SETLE:   return X86::COND_BE;
4078   case ISD::SETONE:
4079   case ISD::SETNE:   return X86::COND_NE;
4080   case ISD::SETUO:   return X86::COND_P;
4081   case ISD::SETO:    return X86::COND_NP;
4082   case ISD::SETOEQ:
4083   case ISD::SETUNE:  return X86::COND_INVALID;
4084   }
4085 }
4086
4087 /// Is there a floating point cmov for the specific X86 condition code?
4088 /// Current x86 isa includes the following FP cmov instructions:
4089 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4090 static bool hasFPCMov(unsigned X86CC) {
4091   switch (X86CC) {
4092   default:
4093     return false;
4094   case X86::COND_B:
4095   case X86::COND_BE:
4096   case X86::COND_E:
4097   case X86::COND_P:
4098   case X86::COND_A:
4099   case X86::COND_AE:
4100   case X86::COND_NE:
4101   case X86::COND_NP:
4102     return true;
4103   }
4104 }
4105
4106 /// Returns true if the target can instruction select the
4107 /// specified FP immediate natively. If false, the legalizer will
4108 /// materialize the FP immediate as a load from a constant pool.
4109 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4110   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4111     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4112       return true;
4113   }
4114   return false;
4115 }
4116
4117 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4118                                               ISD::LoadExtType ExtTy,
4119                                               EVT NewVT) const {
4120   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4121   // relocation target a movq or addq instruction: don't let the load shrink.
4122   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4123   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4124     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4125       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4126   return true;
4127 }
4128
4129 /// \brief Returns true if it is beneficial to convert a load of a constant
4130 /// to just the constant itself.
4131 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4132                                                           Type *Ty) const {
4133   assert(Ty->isIntegerTy());
4134
4135   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4136   if (BitSize == 0 || BitSize > 64)
4137     return false;
4138   return true;
4139 }
4140
4141 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4142                                                 unsigned Index) const {
4143   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4144     return false;
4145
4146   return (Index == 0 || Index == ResVT.getVectorNumElements());
4147 }
4148
4149 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4150   // Speculate cttz only if we can directly use TZCNT.
4151   return Subtarget->hasBMI();
4152 }
4153
4154 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4155   // Speculate ctlz only if we can directly use LZCNT.
4156   return Subtarget->hasLZCNT();
4157 }
4158
4159 /// Return true if every element in Mask, beginning
4160 /// from position Pos and ending in Pos+Size is undef.
4161 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4162   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4163     if (0 <= Mask[i])
4164       return false;
4165   return true;
4166 }
4167
4168 /// Return true if Val is undef or if its value falls within the
4169 /// specified range (L, H].
4170 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4171   return (Val < 0) || (Val >= Low && Val < Hi);
4172 }
4173
4174 /// Val is either less than zero (undef) or equal to the specified value.
4175 static bool isUndefOrEqual(int Val, int CmpVal) {
4176   return (Val < 0 || Val == CmpVal);
4177 }
4178
4179 /// Return true if every element in Mask, beginning
4180 /// from position Pos and ending in Pos+Size, falls within the specified
4181 /// sequential range (Low, Low+Size]. or is undef.
4182 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4183                                        unsigned Pos, unsigned Size, int Low) {
4184   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4185     if (!isUndefOrEqual(Mask[i], Low))
4186       return false;
4187   return true;
4188 }
4189
4190 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4191 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4192 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4193   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4194   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4195     return false;
4196
4197   // The index should be aligned on a vecWidth-bit boundary.
4198   uint64_t Index =
4199     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4200
4201   MVT VT = N->getSimpleValueType(0);
4202   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4203   bool Result = (Index * ElSize) % vecWidth == 0;
4204
4205   return Result;
4206 }
4207
4208 /// Return true if the specified INSERT_SUBVECTOR
4209 /// operand specifies a subvector insert that is suitable for input to
4210 /// insertion of 128 or 256-bit subvectors
4211 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4212   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4213   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4214     return false;
4215   // The index should be aligned on a vecWidth-bit boundary.
4216   uint64_t Index =
4217     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4218
4219   MVT VT = N->getSimpleValueType(0);
4220   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4221   bool Result = (Index * ElSize) % vecWidth == 0;
4222
4223   return Result;
4224 }
4225
4226 bool X86::isVINSERT128Index(SDNode *N) {
4227   return isVINSERTIndex(N, 128);
4228 }
4229
4230 bool X86::isVINSERT256Index(SDNode *N) {
4231   return isVINSERTIndex(N, 256);
4232 }
4233
4234 bool X86::isVEXTRACT128Index(SDNode *N) {
4235   return isVEXTRACTIndex(N, 128);
4236 }
4237
4238 bool X86::isVEXTRACT256Index(SDNode *N) {
4239   return isVEXTRACTIndex(N, 256);
4240 }
4241
4242 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4243   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4244   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4245     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4246
4247   uint64_t Index =
4248     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4249
4250   MVT VecVT = N->getOperand(0).getSimpleValueType();
4251   MVT ElVT = VecVT.getVectorElementType();
4252
4253   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4254   return Index / NumElemsPerChunk;
4255 }
4256
4257 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4258   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4259   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4260     llvm_unreachable("Illegal insert subvector for VINSERT");
4261
4262   uint64_t Index =
4263     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4264
4265   MVT VecVT = N->getSimpleValueType(0);
4266   MVT ElVT = VecVT.getVectorElementType();
4267
4268   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4269   return Index / NumElemsPerChunk;
4270 }
4271
4272 /// Return the appropriate immediate to extract the specified
4273 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4274 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4275   return getExtractVEXTRACTImmediate(N, 128);
4276 }
4277
4278 /// Return the appropriate immediate to extract the specified
4279 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4280 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4281   return getExtractVEXTRACTImmediate(N, 256);
4282 }
4283
4284 /// Return the appropriate immediate to insert at the specified
4285 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4286 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4287   return getInsertVINSERTImmediate(N, 128);
4288 }
4289
4290 /// Return the appropriate immediate to insert at the specified
4291 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4292 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4293   return getInsertVINSERTImmediate(N, 256);
4294 }
4295
4296 /// Returns true if V is a constant integer zero.
4297 static bool isZero(SDValue V) {
4298   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4299   return C && C->isNullValue();
4300 }
4301
4302 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4303 bool X86::isZeroNode(SDValue Elt) {
4304   if (isZero(Elt))
4305     return true;
4306   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4307     return CFP->getValueAPF().isPosZero();
4308   return false;
4309 }
4310
4311 // Build a vector of constants
4312 // Use an UNDEF node if MaskElt == -1.
4313 // Spilt 64-bit constants in the 32-bit mode.
4314 static SDValue getConstVector(ArrayRef<int> Values, EVT VT,
4315                               SelectionDAG &DAG,
4316                               SDLoc dl, bool IsMask = false) {
4317
4318   SmallVector<SDValue, 32>  Ops;
4319   bool Split = false;
4320
4321   EVT ConstVecVT = VT;
4322   unsigned NumElts = VT.getVectorNumElements();
4323   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4324   if (!In64BitMode && VT.getScalarType() == MVT::i64) {
4325     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4326     Split = true;
4327   }
4328
4329   EVT EltVT = ConstVecVT.getScalarType();
4330   for (unsigned i = 0; i < NumElts; ++i) {
4331     bool IsUndef = Values[i] < 0 && IsMask;
4332     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4333       DAG.getConstant(Values[i], dl, EltVT);
4334     Ops.push_back(OpNode);
4335     if (Split)
4336       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4337                     DAG.getConstant(0, dl, EltVT));
4338   }
4339   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4340   if (Split)
4341     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4342   return ConstsNode;
4343 }
4344
4345 /// Returns a vector of specified type with all zero elements.
4346 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4347                              SelectionDAG &DAG, SDLoc dl) {
4348   assert(VT.isVector() && "Expected a vector type");
4349
4350   // Always build SSE zero vectors as <4 x i32> bitcasted
4351   // to their dest type. This ensures they get CSE'd.
4352   SDValue Vec;
4353   if (VT.is128BitVector()) {  // SSE
4354     if (Subtarget->hasSSE2()) {  // SSE2
4355       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4356       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4357     } else { // SSE1
4358       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4359       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4360     }
4361   } else if (VT.is256BitVector()) { // AVX
4362     if (Subtarget->hasInt256()) { // AVX2
4363       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4364       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4365       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4366     } else {
4367       // 256-bit logic and arithmetic instructions in AVX are all
4368       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4369       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4370       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4371       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4372     }
4373   } else if (VT.is512BitVector()) { // AVX-512
4374       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4375       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4376                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4377       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4378   } else if (VT.getScalarType() == MVT::i1) {
4379
4380     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4381             && "Unexpected vector type");
4382     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4383             && "Unexpected vector type");
4384     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4385     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4386     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4387   } else
4388     llvm_unreachable("Unexpected vector type");
4389
4390   return DAG.getBitcast(VT, Vec);
4391 }
4392
4393 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4394                                 SelectionDAG &DAG, SDLoc dl,
4395                                 unsigned vectorWidth) {
4396   assert((vectorWidth == 128 || vectorWidth == 256) &&
4397          "Unsupported vector width");
4398   EVT VT = Vec.getValueType();
4399   EVT ElVT = VT.getVectorElementType();
4400   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4401   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4402                                   VT.getVectorNumElements()/Factor);
4403
4404   // Extract from UNDEF is UNDEF.
4405   if (Vec.getOpcode() == ISD::UNDEF)
4406     return DAG.getUNDEF(ResultVT);
4407
4408   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4409   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4410
4411   // This is the index of the first element of the vectorWidth-bit chunk
4412   // we want.
4413   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4414                                * ElemsPerChunk);
4415
4416   // If the input is a buildvector just emit a smaller one.
4417   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4418     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4419                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4420                                     ElemsPerChunk));
4421
4422   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4423   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4424 }
4425
4426 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4427 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4428 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4429 /// instructions or a simple subregister reference. Idx is an index in the
4430 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4431 /// lowering EXTRACT_VECTOR_ELT operations easier.
4432 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4433                                    SelectionDAG &DAG, SDLoc dl) {
4434   assert((Vec.getValueType().is256BitVector() ||
4435           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4436   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4437 }
4438
4439 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4440 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4441                                    SelectionDAG &DAG, SDLoc dl) {
4442   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4443   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4444 }
4445
4446 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4447                                unsigned IdxVal, SelectionDAG &DAG,
4448                                SDLoc dl, unsigned vectorWidth) {
4449   assert((vectorWidth == 128 || vectorWidth == 256) &&
4450          "Unsupported vector width");
4451   // Inserting UNDEF is Result
4452   if (Vec.getOpcode() == ISD::UNDEF)
4453     return Result;
4454   EVT VT = Vec.getValueType();
4455   EVT ElVT = VT.getVectorElementType();
4456   EVT ResultVT = Result.getValueType();
4457
4458   // Insert the relevant vectorWidth bits.
4459   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4460
4461   // This is the index of the first element of the vectorWidth-bit chunk
4462   // we want.
4463   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4464                                * ElemsPerChunk);
4465
4466   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4467   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4468 }
4469
4470 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4471 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4472 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4473 /// simple superregister reference.  Idx is an index in the 128 bits
4474 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4475 /// lowering INSERT_VECTOR_ELT operations easier.
4476 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4477                                   SelectionDAG &DAG, SDLoc dl) {
4478   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4479
4480   // For insertion into the zero index (low half) of a 256-bit vector, it is
4481   // more efficient to generate a blend with immediate instead of an insert*128.
4482   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4483   // extend the subvector to the size of the result vector. Make sure that
4484   // we are not recursing on that node by checking for undef here.
4485   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4486       Result.getOpcode() != ISD::UNDEF) {
4487     EVT ResultVT = Result.getValueType();
4488     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4489     SDValue Undef = DAG.getUNDEF(ResultVT);
4490     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4491                                  Vec, ZeroIndex);
4492
4493     // The blend instruction, and therefore its mask, depend on the data type.
4494     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4495     if (ScalarType.isFloatingPoint()) {
4496       // Choose either vblendps (float) or vblendpd (double).
4497       unsigned ScalarSize = ScalarType.getSizeInBits();
4498       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4499       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4500       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4501       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4502     }
4503
4504     const X86Subtarget &Subtarget =
4505     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4506
4507     // AVX2 is needed for 256-bit integer blend support.
4508     // Integers must be cast to 32-bit because there is only vpblendd;
4509     // vpblendw can't be used for this because it has a handicapped mask.
4510
4511     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4512     // is still more efficient than using the wrong domain vinsertf128 that
4513     // will be created by InsertSubVector().
4514     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4515
4516     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4517     Vec256 = DAG.getBitcast(CastVT, Vec256);
4518     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4519     return DAG.getBitcast(ResultVT, Vec256);
4520   }
4521
4522   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4523 }
4524
4525 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4526                                   SelectionDAG &DAG, SDLoc dl) {
4527   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4528   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4529 }
4530
4531 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4532 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4533 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4534 /// large BUILD_VECTORS.
4535 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4536                                    unsigned NumElems, SelectionDAG &DAG,
4537                                    SDLoc dl) {
4538   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4539   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4540 }
4541
4542 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4543                                    unsigned NumElems, SelectionDAG &DAG,
4544                                    SDLoc dl) {
4545   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4546   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4547 }
4548
4549 /// Returns a vector of specified type with all bits set.
4550 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4551 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4552 /// Then bitcast to their original type, ensuring they get CSE'd.
4553 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4554                              SelectionDAG &DAG, SDLoc dl) {
4555   assert(VT.isVector() && "Expected a vector type");
4556
4557   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4558   SDValue Vec;
4559   if (VT.is512BitVector()) {
4560     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4561                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4562     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4563   } else if (VT.is256BitVector()) {
4564     if (Subtarget->hasInt256()) { // AVX2
4565       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4566       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4567     } else { // AVX
4568       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4569       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4570     }
4571   } else if (VT.is128BitVector()) {
4572     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4573   } else
4574     llvm_unreachable("Unexpected vector type");
4575
4576   return DAG.getBitcast(VT, Vec);
4577 }
4578
4579 /// Returns a vector_shuffle node for an unpackl operation.
4580 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4581                           SDValue V2) {
4582   unsigned NumElems = VT.getVectorNumElements();
4583   SmallVector<int, 8> Mask;
4584   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4585     Mask.push_back(i);
4586     Mask.push_back(i + NumElems);
4587   }
4588   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4589 }
4590
4591 /// Returns a vector_shuffle node for an unpackh operation.
4592 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4593                           SDValue V2) {
4594   unsigned NumElems = VT.getVectorNumElements();
4595   SmallVector<int, 8> Mask;
4596   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4597     Mask.push_back(i + Half);
4598     Mask.push_back(i + NumElems + Half);
4599   }
4600   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4601 }
4602
4603 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4604 /// This produces a shuffle where the low element of V2 is swizzled into the
4605 /// zero/undef vector, landing at element Idx.
4606 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4607 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4608                                            bool IsZero,
4609                                            const X86Subtarget *Subtarget,
4610                                            SelectionDAG &DAG) {
4611   MVT VT = V2.getSimpleValueType();
4612   SDValue V1 = IsZero
4613     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4614   unsigned NumElems = VT.getVectorNumElements();
4615   SmallVector<int, 16> MaskVec;
4616   for (unsigned i = 0; i != NumElems; ++i)
4617     // If this is the insertion idx, put the low elt of V2 here.
4618     MaskVec.push_back(i == Idx ? NumElems : i);
4619   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4620 }
4621
4622 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4623 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4624 /// uses one source. Note that this will set IsUnary for shuffles which use a
4625 /// single input multiple times, and in those cases it will
4626 /// adjust the mask to only have indices within that single input.
4627 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4628 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4629                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4630   unsigned NumElems = VT.getVectorNumElements();
4631   SDValue ImmN;
4632
4633   IsUnary = false;
4634   bool IsFakeUnary = false;
4635   switch(N->getOpcode()) {
4636   case X86ISD::BLENDI:
4637     ImmN = N->getOperand(N->getNumOperands()-1);
4638     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4639     break;
4640   case X86ISD::SHUFP:
4641     ImmN = N->getOperand(N->getNumOperands()-1);
4642     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4643     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4644     break;
4645   case X86ISD::UNPCKH:
4646     DecodeUNPCKHMask(VT, Mask);
4647     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4648     break;
4649   case X86ISD::UNPCKL:
4650     DecodeUNPCKLMask(VT, Mask);
4651     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4652     break;
4653   case X86ISD::MOVHLPS:
4654     DecodeMOVHLPSMask(NumElems, Mask);
4655     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4656     break;
4657   case X86ISD::MOVLHPS:
4658     DecodeMOVLHPSMask(NumElems, Mask);
4659     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4660     break;
4661   case X86ISD::PALIGNR:
4662     ImmN = N->getOperand(N->getNumOperands()-1);
4663     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4664     break;
4665   case X86ISD::PSHUFD:
4666   case X86ISD::VPERMILPI:
4667     ImmN = N->getOperand(N->getNumOperands()-1);
4668     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4669     IsUnary = true;
4670     break;
4671   case X86ISD::PSHUFHW:
4672     ImmN = N->getOperand(N->getNumOperands()-1);
4673     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4674     IsUnary = true;
4675     break;
4676   case X86ISD::PSHUFLW:
4677     ImmN = N->getOperand(N->getNumOperands()-1);
4678     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4679     IsUnary = true;
4680     break;
4681   case X86ISD::PSHUFB: {
4682     IsUnary = true;
4683     SDValue MaskNode = N->getOperand(1);
4684     while (MaskNode->getOpcode() == ISD::BITCAST)
4685       MaskNode = MaskNode->getOperand(0);
4686
4687     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4688       // If we have a build-vector, then things are easy.
4689       EVT VT = MaskNode.getValueType();
4690       assert(VT.isVector() &&
4691              "Can't produce a non-vector with a build_vector!");
4692       if (!VT.isInteger())
4693         return false;
4694
4695       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4696
4697       SmallVector<uint64_t, 32> RawMask;
4698       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4699         SDValue Op = MaskNode->getOperand(i);
4700         if (Op->getOpcode() == ISD::UNDEF) {
4701           RawMask.push_back((uint64_t)SM_SentinelUndef);
4702           continue;
4703         }
4704         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4705         if (!CN)
4706           return false;
4707         APInt MaskElement = CN->getAPIntValue();
4708
4709         // We now have to decode the element which could be any integer size and
4710         // extract each byte of it.
4711         for (int j = 0; j < NumBytesPerElement; ++j) {
4712           // Note that this is x86 and so always little endian: the low byte is
4713           // the first byte of the mask.
4714           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4715           MaskElement = MaskElement.lshr(8);
4716         }
4717       }
4718       DecodePSHUFBMask(RawMask, Mask);
4719       break;
4720     }
4721
4722     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4723     if (!MaskLoad)
4724       return false;
4725
4726     SDValue Ptr = MaskLoad->getBasePtr();
4727     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4728         Ptr->getOpcode() == X86ISD::WrapperRIP)
4729       Ptr = Ptr->getOperand(0);
4730
4731     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4732     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4733       return false;
4734
4735     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4736       DecodePSHUFBMask(C, Mask);
4737       if (Mask.empty())
4738         return false;
4739       break;
4740     }
4741
4742     return false;
4743   }
4744   case X86ISD::VPERMI:
4745     ImmN = N->getOperand(N->getNumOperands()-1);
4746     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4747     IsUnary = true;
4748     break;
4749   case X86ISD::MOVSS:
4750   case X86ISD::MOVSD:
4751     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4752     break;
4753   case X86ISD::VPERM2X128:
4754     ImmN = N->getOperand(N->getNumOperands()-1);
4755     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4756     if (Mask.empty()) return false;
4757     // Mask only contains negative index if an element is zero.
4758     if (std::any_of(Mask.begin(), Mask.end(),
4759                     [](int M){ return M == SM_SentinelZero; }))
4760       return false;
4761     break;
4762   case X86ISD::MOVSLDUP:
4763     DecodeMOVSLDUPMask(VT, Mask);
4764     IsUnary = true;
4765     break;
4766   case X86ISD::MOVSHDUP:
4767     DecodeMOVSHDUPMask(VT, Mask);
4768     IsUnary = true;
4769     break;
4770   case X86ISD::MOVDDUP:
4771     DecodeMOVDDUPMask(VT, Mask);
4772     IsUnary = true;
4773     break;
4774   case X86ISD::MOVLHPD:
4775   case X86ISD::MOVLPD:
4776   case X86ISD::MOVLPS:
4777     // Not yet implemented
4778     return false;
4779   case X86ISD::VPERMV: {
4780     IsUnary = true;
4781     SDValue MaskNode = N->getOperand(0);
4782     while (MaskNode->getOpcode() == ISD::BITCAST)
4783       MaskNode = MaskNode->getOperand(0);
4784
4785     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4786     SmallVector<uint64_t, 32> RawMask;
4787     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4788       // If we have a build-vector, then things are easy.
4789       assert(MaskNode.getValueType().isInteger() &&
4790              MaskNode.getValueType().getVectorNumElements() ==
4791              VT.getVectorNumElements());
4792
4793       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4794         SDValue Op = MaskNode->getOperand(i);
4795         if (Op->getOpcode() == ISD::UNDEF)
4796           RawMask.push_back((uint64_t)SM_SentinelUndef);
4797         else if (isa<ConstantSDNode>(Op)) {
4798           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4799           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4800         } else
4801           return false;
4802       }
4803       DecodeVPERMVMask(RawMask, Mask);
4804       break;
4805     }
4806     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4807       unsigned NumEltsInMask = MaskNode->getNumOperands();
4808       MaskNode = MaskNode->getOperand(0);
4809       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4810       if (CN) {
4811         APInt MaskEltValue = CN->getAPIntValue();
4812         for (unsigned i = 0; i < NumEltsInMask; ++i)
4813           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4814         DecodeVPERMVMask(RawMask, Mask);
4815         break;
4816       }
4817       // It may be a scalar load
4818     }
4819
4820     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4821     if (!MaskLoad)
4822       return false;
4823
4824     SDValue Ptr = MaskLoad->getBasePtr();
4825     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4826         Ptr->getOpcode() == X86ISD::WrapperRIP)
4827       Ptr = Ptr->getOperand(0);
4828
4829     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4830     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4831       return false;
4832
4833     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4834     if (C) {
4835       DecodeVPERMVMask(C, VT, Mask);
4836       if (Mask.empty())
4837         return false;
4838       break;
4839     }
4840     return false;
4841   }
4842   case X86ISD::VPERMV3: {
4843     IsUnary = false;
4844     SDValue MaskNode = N->getOperand(1);
4845     while (MaskNode->getOpcode() == ISD::BITCAST)
4846       MaskNode = MaskNode->getOperand(1);
4847
4848     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4849       // If we have a build-vector, then things are easy.
4850       assert(MaskNode.getValueType().isInteger() &&
4851              MaskNode.getValueType().getVectorNumElements() ==
4852              VT.getVectorNumElements());
4853
4854       SmallVector<uint64_t, 32> RawMask;
4855       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4856
4857       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4858         SDValue Op = MaskNode->getOperand(i);
4859         if (Op->getOpcode() == ISD::UNDEF)
4860           RawMask.push_back((uint64_t)SM_SentinelUndef);
4861         else {
4862           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4863           if (!CN)
4864             return false;
4865           APInt MaskElement = CN->getAPIntValue();
4866           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4867         }
4868       }
4869       DecodeVPERMV3Mask(RawMask, Mask);
4870       break;
4871     }
4872
4873     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4874     if (!MaskLoad)
4875       return false;
4876
4877     SDValue Ptr = MaskLoad->getBasePtr();
4878     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4879         Ptr->getOpcode() == X86ISD::WrapperRIP)
4880       Ptr = Ptr->getOperand(0);
4881
4882     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4883     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4884       return false;
4885
4886     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4887     if (C) {
4888       DecodeVPERMV3Mask(C, VT, Mask);
4889       if (Mask.empty())
4890         return false;
4891       break;
4892     }
4893     return false;
4894   }
4895   default: llvm_unreachable("unknown target shuffle node");
4896   }
4897
4898   // If we have a fake unary shuffle, the shuffle mask is spread across two
4899   // inputs that are actually the same node. Re-map the mask to always point
4900   // into the first input.
4901   if (IsFakeUnary)
4902     for (int &M : Mask)
4903       if (M >= (int)Mask.size())
4904         M -= Mask.size();
4905
4906   return true;
4907 }
4908
4909 /// Returns the scalar element that will make up the ith
4910 /// element of the result of the vector shuffle.
4911 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4912                                    unsigned Depth) {
4913   if (Depth == 6)
4914     return SDValue();  // Limit search depth.
4915
4916   SDValue V = SDValue(N, 0);
4917   EVT VT = V.getValueType();
4918   unsigned Opcode = V.getOpcode();
4919
4920   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4921   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4922     int Elt = SV->getMaskElt(Index);
4923
4924     if (Elt < 0)
4925       return DAG.getUNDEF(VT.getVectorElementType());
4926
4927     unsigned NumElems = VT.getVectorNumElements();
4928     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4929                                          : SV->getOperand(1);
4930     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4931   }
4932
4933   // Recurse into target specific vector shuffles to find scalars.
4934   if (isTargetShuffle(Opcode)) {
4935     MVT ShufVT = V.getSimpleValueType();
4936     unsigned NumElems = ShufVT.getVectorNumElements();
4937     SmallVector<int, 16> ShuffleMask;
4938     bool IsUnary;
4939
4940     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4941       return SDValue();
4942
4943     int Elt = ShuffleMask[Index];
4944     if (Elt < 0)
4945       return DAG.getUNDEF(ShufVT.getVectorElementType());
4946
4947     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4948                                          : N->getOperand(1);
4949     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4950                                Depth+1);
4951   }
4952
4953   // Actual nodes that may contain scalar elements
4954   if (Opcode == ISD::BITCAST) {
4955     V = V.getOperand(0);
4956     EVT SrcVT = V.getValueType();
4957     unsigned NumElems = VT.getVectorNumElements();
4958
4959     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4960       return SDValue();
4961   }
4962
4963   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4964     return (Index == 0) ? V.getOperand(0)
4965                         : DAG.getUNDEF(VT.getVectorElementType());
4966
4967   if (V.getOpcode() == ISD::BUILD_VECTOR)
4968     return V.getOperand(Index);
4969
4970   return SDValue();
4971 }
4972
4973 /// Custom lower build_vector of v16i8.
4974 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4975                                        unsigned NumNonZero, unsigned NumZero,
4976                                        SelectionDAG &DAG,
4977                                        const X86Subtarget* Subtarget,
4978                                        const TargetLowering &TLI) {
4979   if (NumNonZero > 8)
4980     return SDValue();
4981
4982   SDLoc dl(Op);
4983   SDValue V;
4984   bool First = true;
4985
4986   // SSE4.1 - use PINSRB to insert each byte directly.
4987   if (Subtarget->hasSSE41()) {
4988     for (unsigned i = 0; i < 16; ++i) {
4989       bool isNonZero = (NonZeros & (1 << i)) != 0;
4990       if (isNonZero) {
4991         if (First) {
4992           if (NumZero)
4993             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4994           else
4995             V = DAG.getUNDEF(MVT::v16i8);
4996           First = false;
4997         }
4998         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4999                         MVT::v16i8, V, Op.getOperand(i),
5000                         DAG.getIntPtrConstant(i, dl));
5001       }
5002     }
5003
5004     return V;
5005   }
5006
5007   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5008   for (unsigned i = 0; i < 16; ++i) {
5009     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5010     if (ThisIsNonZero && First) {
5011       if (NumZero)
5012         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5013       else
5014         V = DAG.getUNDEF(MVT::v8i16);
5015       First = false;
5016     }
5017
5018     if ((i & 1) != 0) {
5019       SDValue ThisElt, LastElt;
5020       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5021       if (LastIsNonZero) {
5022         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5023                               MVT::i16, Op.getOperand(i-1));
5024       }
5025       if (ThisIsNonZero) {
5026         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5027         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5028                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5029         if (LastIsNonZero)
5030           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5031       } else
5032         ThisElt = LastElt;
5033
5034       if (ThisElt.getNode())
5035         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5036                         DAG.getIntPtrConstant(i/2, dl));
5037     }
5038   }
5039
5040   return DAG.getBitcast(MVT::v16i8, V);
5041 }
5042
5043 /// Custom lower build_vector of v8i16.
5044 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5045                                      unsigned NumNonZero, unsigned NumZero,
5046                                      SelectionDAG &DAG,
5047                                      const X86Subtarget* Subtarget,
5048                                      const TargetLowering &TLI) {
5049   if (NumNonZero > 4)
5050     return SDValue();
5051
5052   SDLoc dl(Op);
5053   SDValue V;
5054   bool First = true;
5055   for (unsigned i = 0; i < 8; ++i) {
5056     bool isNonZero = (NonZeros & (1 << i)) != 0;
5057     if (isNonZero) {
5058       if (First) {
5059         if (NumZero)
5060           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5061         else
5062           V = DAG.getUNDEF(MVT::v8i16);
5063         First = false;
5064       }
5065       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5066                       MVT::v8i16, V, Op.getOperand(i),
5067                       DAG.getIntPtrConstant(i, dl));
5068     }
5069   }
5070
5071   return V;
5072 }
5073
5074 /// Custom lower build_vector of v4i32 or v4f32.
5075 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5076                                      const X86Subtarget *Subtarget,
5077                                      const TargetLowering &TLI) {
5078   // Find all zeroable elements.
5079   std::bitset<4> Zeroable;
5080   for (int i=0; i < 4; ++i) {
5081     SDValue Elt = Op->getOperand(i);
5082     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5083   }
5084   assert(Zeroable.size() - Zeroable.count() > 1 &&
5085          "We expect at least two non-zero elements!");
5086
5087   // We only know how to deal with build_vector nodes where elements are either
5088   // zeroable or extract_vector_elt with constant index.
5089   SDValue FirstNonZero;
5090   unsigned FirstNonZeroIdx;
5091   for (unsigned i=0; i < 4; ++i) {
5092     if (Zeroable[i])
5093       continue;
5094     SDValue Elt = Op->getOperand(i);
5095     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5096         !isa<ConstantSDNode>(Elt.getOperand(1)))
5097       return SDValue();
5098     // Make sure that this node is extracting from a 128-bit vector.
5099     MVT VT = Elt.getOperand(0).getSimpleValueType();
5100     if (!VT.is128BitVector())
5101       return SDValue();
5102     if (!FirstNonZero.getNode()) {
5103       FirstNonZero = Elt;
5104       FirstNonZeroIdx = i;
5105     }
5106   }
5107
5108   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5109   SDValue V1 = FirstNonZero.getOperand(0);
5110   MVT VT = V1.getSimpleValueType();
5111
5112   // See if this build_vector can be lowered as a blend with zero.
5113   SDValue Elt;
5114   unsigned EltMaskIdx, EltIdx;
5115   int Mask[4];
5116   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5117     if (Zeroable[EltIdx]) {
5118       // The zero vector will be on the right hand side.
5119       Mask[EltIdx] = EltIdx+4;
5120       continue;
5121     }
5122
5123     Elt = Op->getOperand(EltIdx);
5124     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5125     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5126     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5127       break;
5128     Mask[EltIdx] = EltIdx;
5129   }
5130
5131   if (EltIdx == 4) {
5132     // Let the shuffle legalizer deal with blend operations.
5133     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5134     if (V1.getSimpleValueType() != VT)
5135       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5136     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5137   }
5138
5139   // See if we can lower this build_vector to a INSERTPS.
5140   if (!Subtarget->hasSSE41())
5141     return SDValue();
5142
5143   SDValue V2 = Elt.getOperand(0);
5144   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5145     V1 = SDValue();
5146
5147   bool CanFold = true;
5148   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5149     if (Zeroable[i])
5150       continue;
5151
5152     SDValue Current = Op->getOperand(i);
5153     SDValue SrcVector = Current->getOperand(0);
5154     if (!V1.getNode())
5155       V1 = SrcVector;
5156     CanFold = SrcVector == V1 &&
5157       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5158   }
5159
5160   if (!CanFold)
5161     return SDValue();
5162
5163   assert(V1.getNode() && "Expected at least two non-zero elements!");
5164   if (V1.getSimpleValueType() != MVT::v4f32)
5165     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5166   if (V2.getSimpleValueType() != MVT::v4f32)
5167     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5168
5169   // Ok, we can emit an INSERTPS instruction.
5170   unsigned ZMask = Zeroable.to_ulong();
5171
5172   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5173   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5174   SDLoc DL(Op);
5175   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5176                                DAG.getIntPtrConstant(InsertPSMask, DL));
5177   return DAG.getBitcast(VT, Result);
5178 }
5179
5180 /// Return a vector logical shift node.
5181 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5182                          unsigned NumBits, SelectionDAG &DAG,
5183                          const TargetLowering &TLI, SDLoc dl) {
5184   assert(VT.is128BitVector() && "Unknown type for VShift");
5185   MVT ShVT = MVT::v2i64;
5186   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5187   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5188   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5189   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5190   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5191   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5192 }
5193
5194 static SDValue
5195 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5196
5197   // Check if the scalar load can be widened into a vector load. And if
5198   // the address is "base + cst" see if the cst can be "absorbed" into
5199   // the shuffle mask.
5200   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5201     SDValue Ptr = LD->getBasePtr();
5202     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5203       return SDValue();
5204     EVT PVT = LD->getValueType(0);
5205     if (PVT != MVT::i32 && PVT != MVT::f32)
5206       return SDValue();
5207
5208     int FI = -1;
5209     int64_t Offset = 0;
5210     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5211       FI = FINode->getIndex();
5212       Offset = 0;
5213     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5214                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5215       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5216       Offset = Ptr.getConstantOperandVal(1);
5217       Ptr = Ptr.getOperand(0);
5218     } else {
5219       return SDValue();
5220     }
5221
5222     // FIXME: 256-bit vector instructions don't require a strict alignment,
5223     // improve this code to support it better.
5224     unsigned RequiredAlign = VT.getSizeInBits()/8;
5225     SDValue Chain = LD->getChain();
5226     // Make sure the stack object alignment is at least 16 or 32.
5227     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5228     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5229       if (MFI->isFixedObjectIndex(FI)) {
5230         // Can't change the alignment. FIXME: It's possible to compute
5231         // the exact stack offset and reference FI + adjust offset instead.
5232         // If someone *really* cares about this. That's the way to implement it.
5233         return SDValue();
5234       } else {
5235         MFI->setObjectAlignment(FI, RequiredAlign);
5236       }
5237     }
5238
5239     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5240     // Ptr + (Offset & ~15).
5241     if (Offset < 0)
5242       return SDValue();
5243     if ((Offset % RequiredAlign) & 3)
5244       return SDValue();
5245     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5246     if (StartOffset) {
5247       SDLoc DL(Ptr);
5248       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5249                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5250     }
5251
5252     int EltNo = (Offset - StartOffset) >> 2;
5253     unsigned NumElems = VT.getVectorNumElements();
5254
5255     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5256     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5257                              LD->getPointerInfo().getWithOffset(StartOffset),
5258                              false, false, false, 0);
5259
5260     SmallVector<int, 8> Mask(NumElems, EltNo);
5261
5262     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5263   }
5264
5265   return SDValue();
5266 }
5267
5268 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5269 /// elements can be replaced by a single large load which has the same value as
5270 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5271 ///
5272 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5273 ///
5274 /// FIXME: we'd also like to handle the case where the last elements are zero
5275 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5276 /// There's even a handy isZeroNode for that purpose.
5277 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5278                                         SDLoc &DL, SelectionDAG &DAG,
5279                                         bool isAfterLegalize) {
5280   unsigned NumElems = Elts.size();
5281
5282   LoadSDNode *LDBase = nullptr;
5283   unsigned LastLoadedElt = -1U;
5284
5285   // For each element in the initializer, see if we've found a load or an undef.
5286   // If we don't find an initial load element, or later load elements are
5287   // non-consecutive, bail out.
5288   for (unsigned i = 0; i < NumElems; ++i) {
5289     SDValue Elt = Elts[i];
5290     // Look through a bitcast.
5291     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5292       Elt = Elt.getOperand(0);
5293     if (!Elt.getNode() ||
5294         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5295       return SDValue();
5296     if (!LDBase) {
5297       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5298         return SDValue();
5299       LDBase = cast<LoadSDNode>(Elt.getNode());
5300       LastLoadedElt = i;
5301       continue;
5302     }
5303     if (Elt.getOpcode() == ISD::UNDEF)
5304       continue;
5305
5306     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5307     EVT LdVT = Elt.getValueType();
5308     // Each loaded element must be the correct fractional portion of the
5309     // requested vector load.
5310     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5311       return SDValue();
5312     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5313       return SDValue();
5314     LastLoadedElt = i;
5315   }
5316
5317   // If we have found an entire vector of loads and undefs, then return a large
5318   // load of the entire vector width starting at the base pointer.  If we found
5319   // consecutive loads for the low half, generate a vzext_load node.
5320   if (LastLoadedElt == NumElems - 1) {
5321     assert(LDBase && "Did not find base load for merging consecutive loads");
5322     EVT EltVT = LDBase->getValueType(0);
5323     // Ensure that the input vector size for the merged loads matches the
5324     // cumulative size of the input elements.
5325     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5326       return SDValue();
5327
5328     if (isAfterLegalize &&
5329         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5330       return SDValue();
5331
5332     SDValue NewLd = SDValue();
5333
5334     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5335                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5336                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5337                         LDBase->getAlignment());
5338
5339     if (LDBase->hasAnyUseOfValue(1)) {
5340       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5341                                      SDValue(LDBase, 1),
5342                                      SDValue(NewLd.getNode(), 1));
5343       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5344       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5345                              SDValue(NewLd.getNode(), 1));
5346     }
5347
5348     return NewLd;
5349   }
5350
5351   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5352   //of a v4i32 / v4f32. It's probably worth generalizing.
5353   EVT EltVT = VT.getVectorElementType();
5354   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5355       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5356     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5357     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5358     SDValue ResNode =
5359         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5360                                 LDBase->getPointerInfo(),
5361                                 LDBase->getAlignment(),
5362                                 false/*isVolatile*/, true/*ReadMem*/,
5363                                 false/*WriteMem*/);
5364
5365     // Make sure the newly-created LOAD is in the same position as LDBase in
5366     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5367     // update uses of LDBase's output chain to use the TokenFactor.
5368     if (LDBase->hasAnyUseOfValue(1)) {
5369       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5370                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5371       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5372       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5373                              SDValue(ResNode.getNode(), 1));
5374     }
5375
5376     return DAG.getBitcast(VT, ResNode);
5377   }
5378   return SDValue();
5379 }
5380
5381 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5382 /// to generate a splat value for the following cases:
5383 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5384 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5385 /// a scalar load, or a constant.
5386 /// The VBROADCAST node is returned when a pattern is found,
5387 /// or SDValue() otherwise.
5388 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5389                                     SelectionDAG &DAG) {
5390   // VBROADCAST requires AVX.
5391   // TODO: Splats could be generated for non-AVX CPUs using SSE
5392   // instructions, but there's less potential gain for only 128-bit vectors.
5393   if (!Subtarget->hasAVX())
5394     return SDValue();
5395
5396   MVT VT = Op.getSimpleValueType();
5397   SDLoc dl(Op);
5398
5399   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5400          "Unsupported vector type for broadcast.");
5401
5402   SDValue Ld;
5403   bool ConstSplatVal;
5404
5405   switch (Op.getOpcode()) {
5406     default:
5407       // Unknown pattern found.
5408       return SDValue();
5409
5410     case ISD::BUILD_VECTOR: {
5411       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5412       BitVector UndefElements;
5413       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5414
5415       // We need a splat of a single value to use broadcast, and it doesn't
5416       // make any sense if the value is only in one element of the vector.
5417       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5418         return SDValue();
5419
5420       Ld = Splat;
5421       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5422                        Ld.getOpcode() == ISD::ConstantFP);
5423
5424       // Make sure that all of the users of a non-constant load are from the
5425       // BUILD_VECTOR node.
5426       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5427         return SDValue();
5428       break;
5429     }
5430
5431     case ISD::VECTOR_SHUFFLE: {
5432       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5433
5434       // Shuffles must have a splat mask where the first element is
5435       // broadcasted.
5436       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5437         return SDValue();
5438
5439       SDValue Sc = Op.getOperand(0);
5440       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5441           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5442
5443         if (!Subtarget->hasInt256())
5444           return SDValue();
5445
5446         // Use the register form of the broadcast instruction available on AVX2.
5447         if (VT.getSizeInBits() >= 256)
5448           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5449         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5450       }
5451
5452       Ld = Sc.getOperand(0);
5453       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5454                        Ld.getOpcode() == ISD::ConstantFP);
5455
5456       // The scalar_to_vector node and the suspected
5457       // load node must have exactly one user.
5458       // Constants may have multiple users.
5459
5460       // AVX-512 has register version of the broadcast
5461       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5462         Ld.getValueType().getSizeInBits() >= 32;
5463       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5464           !hasRegVer))
5465         return SDValue();
5466       break;
5467     }
5468   }
5469
5470   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5471   bool IsGE256 = (VT.getSizeInBits() >= 256);
5472
5473   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5474   // instruction to save 8 or more bytes of constant pool data.
5475   // TODO: If multiple splats are generated to load the same constant,
5476   // it may be detrimental to overall size. There needs to be a way to detect
5477   // that condition to know if this is truly a size win.
5478   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5479
5480   // Handle broadcasting a single constant scalar from the constant pool
5481   // into a vector.
5482   // On Sandybridge (no AVX2), it is still better to load a constant vector
5483   // from the constant pool and not to broadcast it from a scalar.
5484   // But override that restriction when optimizing for size.
5485   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5486   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5487     EVT CVT = Ld.getValueType();
5488     assert(!CVT.isVector() && "Must not broadcast a vector type");
5489
5490     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5491     // For size optimization, also splat v2f64 and v2i64, and for size opt
5492     // with AVX2, also splat i8 and i16.
5493     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5494     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5495         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5496       const Constant *C = nullptr;
5497       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5498         C = CI->getConstantIntValue();
5499       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5500         C = CF->getConstantFPValue();
5501
5502       assert(C && "Invalid constant type");
5503
5504       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5505       SDValue CP =
5506           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5507       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5508       Ld = DAG.getLoad(
5509           CVT, dl, DAG.getEntryNode(), CP,
5510           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5511           false, false, Alignment);
5512
5513       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5514     }
5515   }
5516
5517   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5518
5519   // Handle AVX2 in-register broadcasts.
5520   if (!IsLoad && Subtarget->hasInt256() &&
5521       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5522     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5523
5524   // The scalar source must be a normal load.
5525   if (!IsLoad)
5526     return SDValue();
5527
5528   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5529       (Subtarget->hasVLX() && ScalarSize == 64))
5530     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5531
5532   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5533   // double since there is no vbroadcastsd xmm
5534   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5535     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5536       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5537   }
5538
5539   // Unsupported broadcast.
5540   return SDValue();
5541 }
5542
5543 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5544 /// underlying vector and index.
5545 ///
5546 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5547 /// index.
5548 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5549                                          SDValue ExtIdx) {
5550   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5551   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5552     return Idx;
5553
5554   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5555   // lowered this:
5556   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5557   // to:
5558   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5559   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5560   //                           undef)
5561   //                       Constant<0>)
5562   // In this case the vector is the extract_subvector expression and the index
5563   // is 2, as specified by the shuffle.
5564   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5565   SDValue ShuffleVec = SVOp->getOperand(0);
5566   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5567   assert(ShuffleVecVT.getVectorElementType() ==
5568          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5569
5570   int ShuffleIdx = SVOp->getMaskElt(Idx);
5571   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5572     ExtractedFromVec = ShuffleVec;
5573     return ShuffleIdx;
5574   }
5575   return Idx;
5576 }
5577
5578 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5579   MVT VT = Op.getSimpleValueType();
5580
5581   // Skip if insert_vec_elt is not supported.
5582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5583   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5584     return SDValue();
5585
5586   SDLoc DL(Op);
5587   unsigned NumElems = Op.getNumOperands();
5588
5589   SDValue VecIn1;
5590   SDValue VecIn2;
5591   SmallVector<unsigned, 4> InsertIndices;
5592   SmallVector<int, 8> Mask(NumElems, -1);
5593
5594   for (unsigned i = 0; i != NumElems; ++i) {
5595     unsigned Opc = Op.getOperand(i).getOpcode();
5596
5597     if (Opc == ISD::UNDEF)
5598       continue;
5599
5600     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5601       // Quit if more than 1 elements need inserting.
5602       if (InsertIndices.size() > 1)
5603         return SDValue();
5604
5605       InsertIndices.push_back(i);
5606       continue;
5607     }
5608
5609     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5610     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5611     // Quit if non-constant index.
5612     if (!isa<ConstantSDNode>(ExtIdx))
5613       return SDValue();
5614     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5615
5616     // Quit if extracted from vector of different type.
5617     if (ExtractedFromVec.getValueType() != VT)
5618       return SDValue();
5619
5620     if (!VecIn1.getNode())
5621       VecIn1 = ExtractedFromVec;
5622     else if (VecIn1 != ExtractedFromVec) {
5623       if (!VecIn2.getNode())
5624         VecIn2 = ExtractedFromVec;
5625       else if (VecIn2 != ExtractedFromVec)
5626         // Quit if more than 2 vectors to shuffle
5627         return SDValue();
5628     }
5629
5630     if (ExtractedFromVec == VecIn1)
5631       Mask[i] = Idx;
5632     else if (ExtractedFromVec == VecIn2)
5633       Mask[i] = Idx + NumElems;
5634   }
5635
5636   if (!VecIn1.getNode())
5637     return SDValue();
5638
5639   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5640   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5641   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5642     unsigned Idx = InsertIndices[i];
5643     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5644                      DAG.getIntPtrConstant(Idx, DL));
5645   }
5646
5647   return NV;
5648 }
5649
5650 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5651   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5652          Op.getScalarValueSizeInBits() == 1 &&
5653          "Can not convert non-constant vector");
5654   uint64_t Immediate = 0;
5655   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5656     SDValue In = Op.getOperand(idx);
5657     if (In.getOpcode() != ISD::UNDEF)
5658       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5659   }
5660   SDLoc dl(Op);
5661   MVT VT =
5662    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5663   return DAG.getConstant(Immediate, dl, VT);
5664 }
5665 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5666 SDValue
5667 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5668
5669   MVT VT = Op.getSimpleValueType();
5670   assert((VT.getVectorElementType() == MVT::i1) &&
5671          "Unexpected type in LowerBUILD_VECTORvXi1!");
5672
5673   SDLoc dl(Op);
5674   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5675     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5676     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5677     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5678   }
5679
5680   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5681     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5682     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5683     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5684   }
5685
5686   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5687     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5688     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5689       return DAG.getBitcast(VT, Imm);
5690     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5691     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5692                         DAG.getIntPtrConstant(0, dl));
5693   }
5694
5695   // Vector has one or more non-const elements
5696   uint64_t Immediate = 0;
5697   SmallVector<unsigned, 16> NonConstIdx;
5698   bool IsSplat = true;
5699   bool HasConstElts = false;
5700   int SplatIdx = -1;
5701   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5702     SDValue In = Op.getOperand(idx);
5703     if (In.getOpcode() == ISD::UNDEF)
5704       continue;
5705     if (!isa<ConstantSDNode>(In))
5706       NonConstIdx.push_back(idx);
5707     else {
5708       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5709       HasConstElts = true;
5710     }
5711     if (SplatIdx == -1)
5712       SplatIdx = idx;
5713     else if (In != Op.getOperand(SplatIdx))
5714       IsSplat = false;
5715   }
5716
5717   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5718   if (IsSplat)
5719     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5720                        DAG.getConstant(1, dl, VT),
5721                        DAG.getConstant(0, dl, VT));
5722
5723   // insert elements one by one
5724   SDValue DstVec;
5725   SDValue Imm;
5726   if (Immediate) {
5727     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5728     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5729   }
5730   else if (HasConstElts)
5731     Imm = DAG.getConstant(0, dl, VT);
5732   else
5733     Imm = DAG.getUNDEF(VT);
5734   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5735     DstVec = DAG.getBitcast(VT, Imm);
5736   else {
5737     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5738     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5739                          DAG.getIntPtrConstant(0, dl));
5740   }
5741
5742   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5743     unsigned InsertIdx = NonConstIdx[i];
5744     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5745                          Op.getOperand(InsertIdx),
5746                          DAG.getIntPtrConstant(InsertIdx, dl));
5747   }
5748   return DstVec;
5749 }
5750
5751 /// \brief Return true if \p N implements a horizontal binop and return the
5752 /// operands for the horizontal binop into V0 and V1.
5753 ///
5754 /// This is a helper function of LowerToHorizontalOp().
5755 /// This function checks that the build_vector \p N in input implements a
5756 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5757 /// operation to match.
5758 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5759 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5760 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5761 /// arithmetic sub.
5762 ///
5763 /// This function only analyzes elements of \p N whose indices are
5764 /// in range [BaseIdx, LastIdx).
5765 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5766                               SelectionDAG &DAG,
5767                               unsigned BaseIdx, unsigned LastIdx,
5768                               SDValue &V0, SDValue &V1) {
5769   EVT VT = N->getValueType(0);
5770
5771   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5772   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5773          "Invalid Vector in input!");
5774
5775   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5776   bool CanFold = true;
5777   unsigned ExpectedVExtractIdx = BaseIdx;
5778   unsigned NumElts = LastIdx - BaseIdx;
5779   V0 = DAG.getUNDEF(VT);
5780   V1 = DAG.getUNDEF(VT);
5781
5782   // Check if N implements a horizontal binop.
5783   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5784     SDValue Op = N->getOperand(i + BaseIdx);
5785
5786     // Skip UNDEFs.
5787     if (Op->getOpcode() == ISD::UNDEF) {
5788       // Update the expected vector extract index.
5789       if (i * 2 == NumElts)
5790         ExpectedVExtractIdx = BaseIdx;
5791       ExpectedVExtractIdx += 2;
5792       continue;
5793     }
5794
5795     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5796
5797     if (!CanFold)
5798       break;
5799
5800     SDValue Op0 = Op.getOperand(0);
5801     SDValue Op1 = Op.getOperand(1);
5802
5803     // Try to match the following pattern:
5804     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5805     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5806         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5807         Op0.getOperand(0) == Op1.getOperand(0) &&
5808         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5809         isa<ConstantSDNode>(Op1.getOperand(1)));
5810     if (!CanFold)
5811       break;
5812
5813     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5814     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5815
5816     if (i * 2 < NumElts) {
5817       if (V0.getOpcode() == ISD::UNDEF) {
5818         V0 = Op0.getOperand(0);
5819         if (V0.getValueType() != VT)
5820           return false;
5821       }
5822     } else {
5823       if (V1.getOpcode() == ISD::UNDEF) {
5824         V1 = Op0.getOperand(0);
5825         if (V1.getValueType() != VT)
5826           return false;
5827       }
5828       if (i * 2 == NumElts)
5829         ExpectedVExtractIdx = BaseIdx;
5830     }
5831
5832     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5833     if (I0 == ExpectedVExtractIdx)
5834       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5835     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5836       // Try to match the following dag sequence:
5837       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5838       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5839     } else
5840       CanFold = false;
5841
5842     ExpectedVExtractIdx += 2;
5843   }
5844
5845   return CanFold;
5846 }
5847
5848 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5849 /// a concat_vector.
5850 ///
5851 /// This is a helper function of LowerToHorizontalOp().
5852 /// This function expects two 256-bit vectors called V0 and V1.
5853 /// At first, each vector is split into two separate 128-bit vectors.
5854 /// Then, the resulting 128-bit vectors are used to implement two
5855 /// horizontal binary operations.
5856 ///
5857 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5858 ///
5859 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5860 /// the two new horizontal binop.
5861 /// When Mode is set, the first horizontal binop dag node would take as input
5862 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5863 /// horizontal binop dag node would take as input the lower 128-bit of V1
5864 /// and the upper 128-bit of V1.
5865 ///   Example:
5866 ///     HADD V0_LO, V0_HI
5867 ///     HADD V1_LO, V1_HI
5868 ///
5869 /// Otherwise, the first horizontal binop dag node takes as input the lower
5870 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5871 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5872 ///   Example:
5873 ///     HADD V0_LO, V1_LO
5874 ///     HADD V0_HI, V1_HI
5875 ///
5876 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5877 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5878 /// the upper 128-bits of the result.
5879 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5880                                      SDLoc DL, SelectionDAG &DAG,
5881                                      unsigned X86Opcode, bool Mode,
5882                                      bool isUndefLO, bool isUndefHI) {
5883   EVT VT = V0.getValueType();
5884   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5885          "Invalid nodes in input!");
5886
5887   unsigned NumElts = VT.getVectorNumElements();
5888   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5889   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5890   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5891   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5892   EVT NewVT = V0_LO.getValueType();
5893
5894   SDValue LO = DAG.getUNDEF(NewVT);
5895   SDValue HI = DAG.getUNDEF(NewVT);
5896
5897   if (Mode) {
5898     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5899     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5900       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5901     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5902       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5903   } else {
5904     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5905     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5906                        V1_LO->getOpcode() != ISD::UNDEF))
5907       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5908
5909     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5910                        V1_HI->getOpcode() != ISD::UNDEF))
5911       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5912   }
5913
5914   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5915 }
5916
5917 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5918 /// node.
5919 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5920                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5921   EVT VT = BV->getValueType(0);
5922   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5923       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5924     return SDValue();
5925
5926   SDLoc DL(BV);
5927   unsigned NumElts = VT.getVectorNumElements();
5928   SDValue InVec0 = DAG.getUNDEF(VT);
5929   SDValue InVec1 = DAG.getUNDEF(VT);
5930
5931   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5932           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5933
5934   // Odd-numbered elements in the input build vector are obtained from
5935   // adding two integer/float elements.
5936   // Even-numbered elements in the input build vector are obtained from
5937   // subtracting two integer/float elements.
5938   unsigned ExpectedOpcode = ISD::FSUB;
5939   unsigned NextExpectedOpcode = ISD::FADD;
5940   bool AddFound = false;
5941   bool SubFound = false;
5942
5943   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5944     SDValue Op = BV->getOperand(i);
5945
5946     // Skip 'undef' values.
5947     unsigned Opcode = Op.getOpcode();
5948     if (Opcode == ISD::UNDEF) {
5949       std::swap(ExpectedOpcode, NextExpectedOpcode);
5950       continue;
5951     }
5952
5953     // Early exit if we found an unexpected opcode.
5954     if (Opcode != ExpectedOpcode)
5955       return SDValue();
5956
5957     SDValue Op0 = Op.getOperand(0);
5958     SDValue Op1 = Op.getOperand(1);
5959
5960     // Try to match the following pattern:
5961     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5962     // Early exit if we cannot match that sequence.
5963     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5964         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5965         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5966         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5967         Op0.getOperand(1) != Op1.getOperand(1))
5968       return SDValue();
5969
5970     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5971     if (I0 != i)
5972       return SDValue();
5973
5974     // We found a valid add/sub node. Update the information accordingly.
5975     if (i & 1)
5976       AddFound = true;
5977     else
5978       SubFound = true;
5979
5980     // Update InVec0 and InVec1.
5981     if (InVec0.getOpcode() == ISD::UNDEF) {
5982       InVec0 = Op0.getOperand(0);
5983       if (InVec0.getValueType() != VT)
5984         return SDValue();
5985     }
5986     if (InVec1.getOpcode() == ISD::UNDEF) {
5987       InVec1 = Op1.getOperand(0);
5988       if (InVec1.getValueType() != VT)
5989         return SDValue();
5990     }
5991
5992     // Make sure that operands in input to each add/sub node always
5993     // come from a same pair of vectors.
5994     if (InVec0 != Op0.getOperand(0)) {
5995       if (ExpectedOpcode == ISD::FSUB)
5996         return SDValue();
5997
5998       // FADD is commutable. Try to commute the operands
5999       // and then test again.
6000       std::swap(Op0, Op1);
6001       if (InVec0 != Op0.getOperand(0))
6002         return SDValue();
6003     }
6004
6005     if (InVec1 != Op1.getOperand(0))
6006       return SDValue();
6007
6008     // Update the pair of expected opcodes.
6009     std::swap(ExpectedOpcode, NextExpectedOpcode);
6010   }
6011
6012   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6013   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6014       InVec1.getOpcode() != ISD::UNDEF)
6015     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6016
6017   return SDValue();
6018 }
6019
6020 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6021 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6022                                    const X86Subtarget *Subtarget,
6023                                    SelectionDAG &DAG) {
6024   EVT VT = BV->getValueType(0);
6025   unsigned NumElts = VT.getVectorNumElements();
6026   unsigned NumUndefsLO = 0;
6027   unsigned NumUndefsHI = 0;
6028   unsigned Half = NumElts/2;
6029
6030   // Count the number of UNDEF operands in the build_vector in input.
6031   for (unsigned i = 0, e = Half; i != e; ++i)
6032     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6033       NumUndefsLO++;
6034
6035   for (unsigned i = Half, e = NumElts; i != e; ++i)
6036     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6037       NumUndefsHI++;
6038
6039   // Early exit if this is either a build_vector of all UNDEFs or all the
6040   // operands but one are UNDEF.
6041   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6042     return SDValue();
6043
6044   SDLoc DL(BV);
6045   SDValue InVec0, InVec1;
6046   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6047     // Try to match an SSE3 float HADD/HSUB.
6048     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6049       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6050
6051     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6052       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6053   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6054     // Try to match an SSSE3 integer HADD/HSUB.
6055     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6056       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6057
6058     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6059       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6060   }
6061
6062   if (!Subtarget->hasAVX())
6063     return SDValue();
6064
6065   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6066     // Try to match an AVX horizontal add/sub of packed single/double
6067     // precision floating point values from 256-bit vectors.
6068     SDValue InVec2, InVec3;
6069     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6070         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6071         ((InVec0.getOpcode() == ISD::UNDEF ||
6072           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6073         ((InVec1.getOpcode() == ISD::UNDEF ||
6074           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6075       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6076
6077     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6078         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6079         ((InVec0.getOpcode() == ISD::UNDEF ||
6080           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6081         ((InVec1.getOpcode() == ISD::UNDEF ||
6082           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6083       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6084   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6085     // Try to match an AVX2 horizontal add/sub of signed integers.
6086     SDValue InVec2, InVec3;
6087     unsigned X86Opcode;
6088     bool CanFold = true;
6089
6090     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6091         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6092         ((InVec0.getOpcode() == ISD::UNDEF ||
6093           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6094         ((InVec1.getOpcode() == ISD::UNDEF ||
6095           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6096       X86Opcode = X86ISD::HADD;
6097     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6098         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6099         ((InVec0.getOpcode() == ISD::UNDEF ||
6100           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6101         ((InVec1.getOpcode() == ISD::UNDEF ||
6102           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6103       X86Opcode = X86ISD::HSUB;
6104     else
6105       CanFold = false;
6106
6107     if (CanFold) {
6108       // Fold this build_vector into a single horizontal add/sub.
6109       // Do this only if the target has AVX2.
6110       if (Subtarget->hasAVX2())
6111         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6112
6113       // Do not try to expand this build_vector into a pair of horizontal
6114       // add/sub if we can emit a pair of scalar add/sub.
6115       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6116         return SDValue();
6117
6118       // Convert this build_vector into a pair of horizontal binop followed by
6119       // a concat vector.
6120       bool isUndefLO = NumUndefsLO == Half;
6121       bool isUndefHI = NumUndefsHI == Half;
6122       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6123                                    isUndefLO, isUndefHI);
6124     }
6125   }
6126
6127   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6128        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6129     unsigned X86Opcode;
6130     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6131       X86Opcode = X86ISD::HADD;
6132     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6133       X86Opcode = X86ISD::HSUB;
6134     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6135       X86Opcode = X86ISD::FHADD;
6136     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6137       X86Opcode = X86ISD::FHSUB;
6138     else
6139       return SDValue();
6140
6141     // Don't try to expand this build_vector into a pair of horizontal add/sub
6142     // if we can simply emit a pair of scalar add/sub.
6143     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6144       return SDValue();
6145
6146     // Convert this build_vector into two horizontal add/sub followed by
6147     // a concat vector.
6148     bool isUndefLO = NumUndefsLO == Half;
6149     bool isUndefHI = NumUndefsHI == Half;
6150     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6151                                  isUndefLO, isUndefHI);
6152   }
6153
6154   return SDValue();
6155 }
6156
6157 SDValue
6158 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6159   SDLoc dl(Op);
6160
6161   MVT VT = Op.getSimpleValueType();
6162   MVT ExtVT = VT.getVectorElementType();
6163   unsigned NumElems = Op.getNumOperands();
6164
6165   // Generate vectors for predicate vectors.
6166   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6167     return LowerBUILD_VECTORvXi1(Op, DAG);
6168
6169   // Vectors containing all zeros can be matched by pxor and xorps later
6170   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6171     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6172     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6173     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6174       return Op;
6175
6176     return getZeroVector(VT, Subtarget, DAG, dl);
6177   }
6178
6179   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6180   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6181   // vpcmpeqd on 256-bit vectors.
6182   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6183     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6184       return Op;
6185
6186     if (!VT.is512BitVector())
6187       return getOnesVector(VT, Subtarget, DAG, dl);
6188   }
6189
6190   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6191   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6192     return AddSub;
6193   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6194     return HorizontalOp;
6195   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6196     return Broadcast;
6197
6198   unsigned EVTBits = ExtVT.getSizeInBits();
6199
6200   unsigned NumZero  = 0;
6201   unsigned NumNonZero = 0;
6202   unsigned NonZeros = 0;
6203   bool IsAllConstants = true;
6204   SmallSet<SDValue, 8> Values;
6205   for (unsigned i = 0; i < NumElems; ++i) {
6206     SDValue Elt = Op.getOperand(i);
6207     if (Elt.getOpcode() == ISD::UNDEF)
6208       continue;
6209     Values.insert(Elt);
6210     if (Elt.getOpcode() != ISD::Constant &&
6211         Elt.getOpcode() != ISD::ConstantFP)
6212       IsAllConstants = false;
6213     if (X86::isZeroNode(Elt))
6214       NumZero++;
6215     else {
6216       NonZeros |= (1 << i);
6217       NumNonZero++;
6218     }
6219   }
6220
6221   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6222   if (NumNonZero == 0)
6223     return DAG.getUNDEF(VT);
6224
6225   // Special case for single non-zero, non-undef, element.
6226   if (NumNonZero == 1) {
6227     unsigned Idx = countTrailingZeros(NonZeros);
6228     SDValue Item = Op.getOperand(Idx);
6229
6230     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6231     // the value are obviously zero, truncate the value to i32 and do the
6232     // insertion that way.  Only do this if the value is non-constant or if the
6233     // value is a constant being inserted into element 0.  It is cheaper to do
6234     // a constant pool load than it is to do a movd + shuffle.
6235     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6236         (!IsAllConstants || Idx == 0)) {
6237       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6238         // Handle SSE only.
6239         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6240         EVT VecVT = MVT::v4i32;
6241
6242         // Truncate the value (which may itself be a constant) to i32, and
6243         // convert it to a vector with movd (S2V+shuffle to zero extend).
6244         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6245         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6246         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6247                                       Item, Idx * 2, true, Subtarget, DAG));
6248       }
6249     }
6250
6251     // If we have a constant or non-constant insertion into the low element of
6252     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6253     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6254     // depending on what the source datatype is.
6255     if (Idx == 0) {
6256       if (NumZero == 0)
6257         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6258
6259       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6260           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6261         if (VT.is512BitVector()) {
6262           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6263           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6264                              Item, DAG.getIntPtrConstant(0, dl));
6265         }
6266         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6267                "Expected an SSE value type!");
6268         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6269         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6270         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6271       }
6272
6273       // We can't directly insert an i8 or i16 into a vector, so zero extend
6274       // it to i32 first.
6275       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6276         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6277         if (VT.is256BitVector()) {
6278           if (Subtarget->hasAVX()) {
6279             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6280             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6281           } else {
6282             // Without AVX, we need to extend to a 128-bit vector and then
6283             // insert into the 256-bit vector.
6284             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6285             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6286             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6287           }
6288         } else {
6289           assert(VT.is128BitVector() && "Expected an SSE value type!");
6290           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6291           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6292         }
6293         return DAG.getBitcast(VT, Item);
6294       }
6295     }
6296
6297     // Is it a vector logical left shift?
6298     if (NumElems == 2 && Idx == 1 &&
6299         X86::isZeroNode(Op.getOperand(0)) &&
6300         !X86::isZeroNode(Op.getOperand(1))) {
6301       unsigned NumBits = VT.getSizeInBits();
6302       return getVShift(true, VT,
6303                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6304                                    VT, Op.getOperand(1)),
6305                        NumBits/2, DAG, *this, dl);
6306     }
6307
6308     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6309       return SDValue();
6310
6311     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6312     // is a non-constant being inserted into an element other than the low one,
6313     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6314     // movd/movss) to move this into the low element, then shuffle it into
6315     // place.
6316     if (EVTBits == 32) {
6317       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6318       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6319     }
6320   }
6321
6322   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6323   if (Values.size() == 1) {
6324     if (EVTBits == 32) {
6325       // Instead of a shuffle like this:
6326       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6327       // Check if it's possible to issue this instead.
6328       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6329       unsigned Idx = countTrailingZeros(NonZeros);
6330       SDValue Item = Op.getOperand(Idx);
6331       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6332         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6333     }
6334     return SDValue();
6335   }
6336
6337   // A vector full of immediates; various special cases are already
6338   // handled, so this is best done with a single constant-pool load.
6339   if (IsAllConstants)
6340     return SDValue();
6341
6342   // For AVX-length vectors, see if we can use a vector load to get all of the
6343   // elements, otherwise build the individual 128-bit pieces and use
6344   // shuffles to put them in place.
6345   if (VT.is256BitVector() || VT.is512BitVector()) {
6346     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6347
6348     // Check for a build vector of consecutive loads.
6349     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6350       return LD;
6351
6352     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6353
6354     // Build both the lower and upper subvector.
6355     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6356                                 makeArrayRef(&V[0], NumElems/2));
6357     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6358                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6359
6360     // Recreate the wider vector with the lower and upper part.
6361     if (VT.is256BitVector())
6362       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6363     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6364   }
6365
6366   // Let legalizer expand 2-wide build_vectors.
6367   if (EVTBits == 64) {
6368     if (NumNonZero == 1) {
6369       // One half is zero or undef.
6370       unsigned Idx = countTrailingZeros(NonZeros);
6371       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6372                                  Op.getOperand(Idx));
6373       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6374     }
6375     return SDValue();
6376   }
6377
6378   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6379   if (EVTBits == 8 && NumElems == 16)
6380     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6381                                         Subtarget, *this))
6382       return V;
6383
6384   if (EVTBits == 16 && NumElems == 8)
6385     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6386                                       Subtarget, *this))
6387       return V;
6388
6389   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6390   if (EVTBits == 32 && NumElems == 4)
6391     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6392       return V;
6393
6394   // If element VT is == 32 bits, turn it into a number of shuffles.
6395   SmallVector<SDValue, 8> V(NumElems);
6396   if (NumElems == 4 && NumZero > 0) {
6397     for (unsigned i = 0; i < 4; ++i) {
6398       bool isZero = !(NonZeros & (1 << i));
6399       if (isZero)
6400         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6401       else
6402         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6403     }
6404
6405     for (unsigned i = 0; i < 2; ++i) {
6406       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6407         default: break;
6408         case 0:
6409           V[i] = V[i*2];  // Must be a zero vector.
6410           break;
6411         case 1:
6412           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6413           break;
6414         case 2:
6415           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6416           break;
6417         case 3:
6418           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6419           break;
6420       }
6421     }
6422
6423     bool Reverse1 = (NonZeros & 0x3) == 2;
6424     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6425     int MaskVec[] = {
6426       Reverse1 ? 1 : 0,
6427       Reverse1 ? 0 : 1,
6428       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6429       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6430     };
6431     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6432   }
6433
6434   if (Values.size() > 1 && VT.is128BitVector()) {
6435     // Check for a build vector of consecutive loads.
6436     for (unsigned i = 0; i < NumElems; ++i)
6437       V[i] = Op.getOperand(i);
6438
6439     // Check for elements which are consecutive loads.
6440     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6441       return LD;
6442
6443     // Check for a build vector from mostly shuffle plus few inserting.
6444     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6445       return Sh;
6446
6447     // For SSE 4.1, use insertps to put the high elements into the low element.
6448     if (Subtarget->hasSSE41()) {
6449       SDValue Result;
6450       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6451         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6452       else
6453         Result = DAG.getUNDEF(VT);
6454
6455       for (unsigned i = 1; i < NumElems; ++i) {
6456         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6457         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6458                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6459       }
6460       return Result;
6461     }
6462
6463     // Otherwise, expand into a number of unpckl*, start by extending each of
6464     // our (non-undef) elements to the full vector width with the element in the
6465     // bottom slot of the vector (which generates no code for SSE).
6466     for (unsigned i = 0; i < NumElems; ++i) {
6467       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6468         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6469       else
6470         V[i] = DAG.getUNDEF(VT);
6471     }
6472
6473     // Next, we iteratively mix elements, e.g. for v4f32:
6474     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6475     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6476     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6477     unsigned EltStride = NumElems >> 1;
6478     while (EltStride != 0) {
6479       for (unsigned i = 0; i < EltStride; ++i) {
6480         // If V[i+EltStride] is undef and this is the first round of mixing,
6481         // then it is safe to just drop this shuffle: V[i] is already in the
6482         // right place, the one element (since it's the first round) being
6483         // inserted as undef can be dropped.  This isn't safe for successive
6484         // rounds because they will permute elements within both vectors.
6485         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6486             EltStride == NumElems/2)
6487           continue;
6488
6489         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6490       }
6491       EltStride >>= 1;
6492     }
6493     return V[0];
6494   }
6495   return SDValue();
6496 }
6497
6498 // 256-bit AVX can use the vinsertf128 instruction
6499 // to create 256-bit vectors from two other 128-bit ones.
6500 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6501   SDLoc dl(Op);
6502   MVT ResVT = Op.getSimpleValueType();
6503
6504   assert((ResVT.is256BitVector() ||
6505           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6506
6507   SDValue V1 = Op.getOperand(0);
6508   SDValue V2 = Op.getOperand(1);
6509   unsigned NumElems = ResVT.getVectorNumElements();
6510   if (ResVT.is256BitVector())
6511     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6512
6513   if (Op.getNumOperands() == 4) {
6514     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6515                                 ResVT.getVectorNumElements()/2);
6516     SDValue V3 = Op.getOperand(2);
6517     SDValue V4 = Op.getOperand(3);
6518     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6519       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6520   }
6521   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6522 }
6523
6524 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6525                                        const X86Subtarget *Subtarget,
6526                                        SelectionDAG & DAG) {
6527   SDLoc dl(Op);
6528   MVT ResVT = Op.getSimpleValueType();
6529   unsigned NumOfOperands = Op.getNumOperands();
6530
6531   assert(isPowerOf2_32(NumOfOperands) &&
6532          "Unexpected number of operands in CONCAT_VECTORS");
6533
6534   if (NumOfOperands > 2) {
6535     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6536                                   ResVT.getVectorNumElements()/2);
6537     SmallVector<SDValue, 2> Ops;
6538     for (unsigned i = 0; i < NumOfOperands/2; i++)
6539       Ops.push_back(Op.getOperand(i));
6540     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6541     Ops.clear();
6542     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6543       Ops.push_back(Op.getOperand(i));
6544     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6545     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6546   }
6547
6548   SDValue V1 = Op.getOperand(0);
6549   SDValue V2 = Op.getOperand(1);
6550   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6551   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6552
6553   if (IsZeroV1 && IsZeroV2)
6554     return getZeroVector(ResVT, Subtarget, DAG, dl);
6555
6556   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6557   SDValue Undef = DAG.getUNDEF(ResVT);
6558   unsigned NumElems = ResVT.getVectorNumElements();
6559   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6560
6561   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6562   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6563   if (IsZeroV1)
6564     return V2;
6565
6566   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6567   // Zero the upper bits of V1
6568   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6569   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6570   if (IsZeroV2)
6571     return V1;
6572   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6573 }
6574
6575 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6576                                    const X86Subtarget *Subtarget,
6577                                    SelectionDAG &DAG) {
6578   MVT VT = Op.getSimpleValueType();
6579   if (VT.getVectorElementType() == MVT::i1)
6580     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6581
6582   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6583          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6584           Op.getNumOperands() == 4)));
6585
6586   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6587   // from two other 128-bit ones.
6588
6589   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6590   return LowerAVXCONCAT_VECTORS(Op, DAG);
6591 }
6592
6593 //===----------------------------------------------------------------------===//
6594 // Vector shuffle lowering
6595 //
6596 // This is an experimental code path for lowering vector shuffles on x86. It is
6597 // designed to handle arbitrary vector shuffles and blends, gracefully
6598 // degrading performance as necessary. It works hard to recognize idiomatic
6599 // shuffles and lower them to optimal instruction patterns without leaving
6600 // a framework that allows reasonably efficient handling of all vector shuffle
6601 // patterns.
6602 //===----------------------------------------------------------------------===//
6603
6604 /// \brief Tiny helper function to identify a no-op mask.
6605 ///
6606 /// This is a somewhat boring predicate function. It checks whether the mask
6607 /// array input, which is assumed to be a single-input shuffle mask of the kind
6608 /// used by the X86 shuffle instructions (not a fully general
6609 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6610 /// in-place shuffle are 'no-op's.
6611 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6612   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6613     if (Mask[i] != -1 && Mask[i] != i)
6614       return false;
6615   return true;
6616 }
6617
6618 /// \brief Helper function to classify a mask as a single-input mask.
6619 ///
6620 /// This isn't a generic single-input test because in the vector shuffle
6621 /// lowering we canonicalize single inputs to be the first input operand. This
6622 /// means we can more quickly test for a single input by only checking whether
6623 /// an input from the second operand exists. We also assume that the size of
6624 /// mask corresponds to the size of the input vectors which isn't true in the
6625 /// fully general case.
6626 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6627   for (int M : Mask)
6628     if (M >= (int)Mask.size())
6629       return false;
6630   return true;
6631 }
6632
6633 /// \brief Test whether there are elements crossing 128-bit lanes in this
6634 /// shuffle mask.
6635 ///
6636 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6637 /// and we routinely test for these.
6638 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6639   int LaneSize = 128 / VT.getScalarSizeInBits();
6640   int Size = Mask.size();
6641   for (int i = 0; i < Size; ++i)
6642     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6643       return true;
6644   return false;
6645 }
6646
6647 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6648 ///
6649 /// This checks a shuffle mask to see if it is performing the same
6650 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6651 /// that it is also not lane-crossing. It may however involve a blend from the
6652 /// same lane of a second vector.
6653 ///
6654 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6655 /// non-trivial to compute in the face of undef lanes. The representation is
6656 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6657 /// entries from both V1 and V2 inputs to the wider mask.
6658 static bool
6659 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6660                                 SmallVectorImpl<int> &RepeatedMask) {
6661   int LaneSize = 128 / VT.getScalarSizeInBits();
6662   RepeatedMask.resize(LaneSize, -1);
6663   int Size = Mask.size();
6664   for (int i = 0; i < Size; ++i) {
6665     if (Mask[i] < 0)
6666       continue;
6667     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6668       // This entry crosses lanes, so there is no way to model this shuffle.
6669       return false;
6670
6671     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6672     if (RepeatedMask[i % LaneSize] == -1)
6673       // This is the first non-undef entry in this slot of a 128-bit lane.
6674       RepeatedMask[i % LaneSize] =
6675           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6676     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6677       // Found a mismatch with the repeated mask.
6678       return false;
6679   }
6680   return true;
6681 }
6682
6683 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6684 /// arguments.
6685 ///
6686 /// This is a fast way to test a shuffle mask against a fixed pattern:
6687 ///
6688 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6689 ///
6690 /// It returns true if the mask is exactly as wide as the argument list, and
6691 /// each element of the mask is either -1 (signifying undef) or the value given
6692 /// in the argument.
6693 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6694                                 ArrayRef<int> ExpectedMask) {
6695   if (Mask.size() != ExpectedMask.size())
6696     return false;
6697
6698   int Size = Mask.size();
6699
6700   // If the values are build vectors, we can look through them to find
6701   // equivalent inputs that make the shuffles equivalent.
6702   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6703   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6704
6705   for (int i = 0; i < Size; ++i)
6706     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6707       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6708       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6709       if (!MaskBV || !ExpectedBV ||
6710           MaskBV->getOperand(Mask[i] % Size) !=
6711               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6712         return false;
6713     }
6714
6715   return true;
6716 }
6717
6718 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6719 ///
6720 /// This helper function produces an 8-bit shuffle immediate corresponding to
6721 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6722 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6723 /// example.
6724 ///
6725 /// NB: We rely heavily on "undef" masks preserving the input lane.
6726 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6727                                           SelectionDAG &DAG) {
6728   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6729   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6730   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6731   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6732   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6733
6734   unsigned Imm = 0;
6735   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6736   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6737   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6738   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6739   return DAG.getConstant(Imm, DL, MVT::i8);
6740 }
6741
6742 /// \brief Compute whether each element of a shuffle is zeroable.
6743 ///
6744 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6745 /// Either it is an undef element in the shuffle mask, the element of the input
6746 /// referenced is undef, or the element of the input referenced is known to be
6747 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6748 /// as many lanes with this technique as possible to simplify the remaining
6749 /// shuffle.
6750 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6751                                                      SDValue V1, SDValue V2) {
6752   SmallBitVector Zeroable(Mask.size(), false);
6753
6754   while (V1.getOpcode() == ISD::BITCAST)
6755     V1 = V1->getOperand(0);
6756   while (V2.getOpcode() == ISD::BITCAST)
6757     V2 = V2->getOperand(0);
6758
6759   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6760   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6761
6762   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6763     int M = Mask[i];
6764     // Handle the easy cases.
6765     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6766       Zeroable[i] = true;
6767       continue;
6768     }
6769
6770     // If this is an index into a build_vector node (which has the same number
6771     // of elements), dig out the input value and use it.
6772     SDValue V = M < Size ? V1 : V2;
6773     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6774       continue;
6775
6776     SDValue Input = V.getOperand(M % Size);
6777     // The UNDEF opcode check really should be dead code here, but not quite
6778     // worth asserting on (it isn't invalid, just unexpected).
6779     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6780       Zeroable[i] = true;
6781   }
6782
6783   return Zeroable;
6784 }
6785
6786 // X86 has dedicated unpack instructions that can handle specific blend
6787 // operations: UNPCKH and UNPCKL.
6788 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6789                                            SDValue V1, SDValue V2,
6790                                            SelectionDAG &DAG) {
6791   int NumElts = VT.getVectorNumElements();
6792   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6793   SmallVector<int, 8> Unpckl;
6794   SmallVector<int, 8> Unpckh;
6795
6796   for (int i = 0; i < NumElts; ++i) {
6797     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6798     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6799     int HiPos = LoPos + NumEltsInLane / 2;
6800     Unpckl.push_back(LoPos);
6801     Unpckh.push_back(HiPos);
6802   }
6803
6804   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6805     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6806   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6807     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6808
6809   // Commute and try again.
6810   ShuffleVectorSDNode::commuteMask(Unpckl);
6811   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6812     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6813
6814   ShuffleVectorSDNode::commuteMask(Unpckh);
6815   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6816     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6817
6818   return SDValue();
6819 }
6820
6821 /// \brief Try to emit a bitmask instruction for a shuffle.
6822 ///
6823 /// This handles cases where we can model a blend exactly as a bitmask due to
6824 /// one of the inputs being zeroable.
6825 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6826                                            SDValue V2, ArrayRef<int> Mask,
6827                                            SelectionDAG &DAG) {
6828   MVT EltVT = VT.getScalarType();
6829   int NumEltBits = EltVT.getSizeInBits();
6830   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6831   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6832   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6833                                     IntEltVT);
6834   if (EltVT.isFloatingPoint()) {
6835     Zero = DAG.getBitcast(EltVT, Zero);
6836     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6837   }
6838   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6839   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6840   SDValue V;
6841   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6842     if (Zeroable[i])
6843       continue;
6844     if (Mask[i] % Size != i)
6845       return SDValue(); // Not a blend.
6846     if (!V)
6847       V = Mask[i] < Size ? V1 : V2;
6848     else if (V != (Mask[i] < Size ? V1 : V2))
6849       return SDValue(); // Can only let one input through the mask.
6850
6851     VMaskOps[i] = AllOnes;
6852   }
6853   if (!V)
6854     return SDValue(); // No non-zeroable elements!
6855
6856   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6857   V = DAG.getNode(VT.isFloatingPoint()
6858                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6859                   DL, VT, V, VMask);
6860   return V;
6861 }
6862
6863 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6864 ///
6865 /// This is used as a fallback approach when first class blend instructions are
6866 /// unavailable. Currently it is only suitable for integer vectors, but could
6867 /// be generalized for floating point vectors if desirable.
6868 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6869                                             SDValue V2, ArrayRef<int> Mask,
6870                                             SelectionDAG &DAG) {
6871   assert(VT.isInteger() && "Only supports integer vector types!");
6872   MVT EltVT = VT.getScalarType();
6873   int NumEltBits = EltVT.getSizeInBits();
6874   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6875   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6876                                     EltVT);
6877   SmallVector<SDValue, 16> MaskOps;
6878   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6879     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6880       return SDValue(); // Shuffled input!
6881     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6882   }
6883
6884   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6885   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6886   // We have to cast V2 around.
6887   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6888   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6889                                       DAG.getBitcast(MaskVT, V1Mask),
6890                                       DAG.getBitcast(MaskVT, V2)));
6891   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6892 }
6893
6894 /// \brief Try to emit a blend instruction for a shuffle.
6895 ///
6896 /// This doesn't do any checks for the availability of instructions for blending
6897 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6898 /// be matched in the backend with the type given. What it does check for is
6899 /// that the shuffle mask is in fact a blend.
6900 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6901                                          SDValue V2, ArrayRef<int> Mask,
6902                                          const X86Subtarget *Subtarget,
6903                                          SelectionDAG &DAG) {
6904   unsigned BlendMask = 0;
6905   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6906     if (Mask[i] >= Size) {
6907       if (Mask[i] != i + Size)
6908         return SDValue(); // Shuffled V2 input!
6909       BlendMask |= 1u << i;
6910       continue;
6911     }
6912     if (Mask[i] >= 0 && Mask[i] != i)
6913       return SDValue(); // Shuffled V1 input!
6914   }
6915   switch (VT.SimpleTy) {
6916   case MVT::v2f64:
6917   case MVT::v4f32:
6918   case MVT::v4f64:
6919   case MVT::v8f32:
6920     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6921                        DAG.getConstant(BlendMask, DL, MVT::i8));
6922
6923   case MVT::v4i64:
6924   case MVT::v8i32:
6925     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6926     // FALLTHROUGH
6927   case MVT::v2i64:
6928   case MVT::v4i32:
6929     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6930     // that instruction.
6931     if (Subtarget->hasAVX2()) {
6932       // Scale the blend by the number of 32-bit dwords per element.
6933       int Scale =  VT.getScalarSizeInBits() / 32;
6934       BlendMask = 0;
6935       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6936         if (Mask[i] >= Size)
6937           for (int j = 0; j < Scale; ++j)
6938             BlendMask |= 1u << (i * Scale + j);
6939
6940       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6941       V1 = DAG.getBitcast(BlendVT, V1);
6942       V2 = DAG.getBitcast(BlendVT, V2);
6943       return DAG.getBitcast(
6944           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6945                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6946     }
6947     // FALLTHROUGH
6948   case MVT::v8i16: {
6949     // For integer shuffles we need to expand the mask and cast the inputs to
6950     // v8i16s prior to blending.
6951     int Scale = 8 / VT.getVectorNumElements();
6952     BlendMask = 0;
6953     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6954       if (Mask[i] >= Size)
6955         for (int j = 0; j < Scale; ++j)
6956           BlendMask |= 1u << (i * Scale + j);
6957
6958     V1 = DAG.getBitcast(MVT::v8i16, V1);
6959     V2 = DAG.getBitcast(MVT::v8i16, V2);
6960     return DAG.getBitcast(VT,
6961                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6962                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6963   }
6964
6965   case MVT::v16i16: {
6966     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6967     SmallVector<int, 8> RepeatedMask;
6968     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6969       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6970       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6971       BlendMask = 0;
6972       for (int i = 0; i < 8; ++i)
6973         if (RepeatedMask[i] >= 16)
6974           BlendMask |= 1u << i;
6975       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6976                          DAG.getConstant(BlendMask, DL, MVT::i8));
6977     }
6978   }
6979     // FALLTHROUGH
6980   case MVT::v16i8:
6981   case MVT::v32i8: {
6982     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6983            "256-bit byte-blends require AVX2 support!");
6984
6985     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6986     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6987       return Masked;
6988
6989     // Scale the blend by the number of bytes per element.
6990     int Scale = VT.getScalarSizeInBits() / 8;
6991
6992     // This form of blend is always done on bytes. Compute the byte vector
6993     // type.
6994     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6995
6996     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6997     // mix of LLVM's code generator and the x86 backend. We tell the code
6998     // generator that boolean values in the elements of an x86 vector register
6999     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7000     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7001     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7002     // of the element (the remaining are ignored) and 0 in that high bit would
7003     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7004     // the LLVM model for boolean values in vector elements gets the relevant
7005     // bit set, it is set backwards and over constrained relative to x86's
7006     // actual model.
7007     SmallVector<SDValue, 32> VSELECTMask;
7008     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7009       for (int j = 0; j < Scale; ++j)
7010         VSELECTMask.push_back(
7011             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7012                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7013                                           MVT::i8));
7014
7015     V1 = DAG.getBitcast(BlendVT, V1);
7016     V2 = DAG.getBitcast(BlendVT, V2);
7017     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7018                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7019                                                       BlendVT, VSELECTMask),
7020                                           V1, V2));
7021   }
7022
7023   default:
7024     llvm_unreachable("Not a supported integer vector type!");
7025   }
7026 }
7027
7028 /// \brief Try to lower as a blend of elements from two inputs followed by
7029 /// a single-input permutation.
7030 ///
7031 /// This matches the pattern where we can blend elements from two inputs and
7032 /// then reduce the shuffle to a single-input permutation.
7033 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7034                                                    SDValue V2,
7035                                                    ArrayRef<int> Mask,
7036                                                    SelectionDAG &DAG) {
7037   // We build up the blend mask while checking whether a blend is a viable way
7038   // to reduce the shuffle.
7039   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7040   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7041
7042   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7043     if (Mask[i] < 0)
7044       continue;
7045
7046     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7047
7048     if (BlendMask[Mask[i] % Size] == -1)
7049       BlendMask[Mask[i] % Size] = Mask[i];
7050     else if (BlendMask[Mask[i] % Size] != Mask[i])
7051       return SDValue(); // Can't blend in the needed input!
7052
7053     PermuteMask[i] = Mask[i] % Size;
7054   }
7055
7056   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7057   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7058 }
7059
7060 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7061 /// blends and permutes.
7062 ///
7063 /// This matches the extremely common pattern for handling combined
7064 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7065 /// operations. It will try to pick the best arrangement of shuffles and
7066 /// blends.
7067 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7068                                                           SDValue V1,
7069                                                           SDValue V2,
7070                                                           ArrayRef<int> Mask,
7071                                                           SelectionDAG &DAG) {
7072   // Shuffle the input elements into the desired positions in V1 and V2 and
7073   // blend them together.
7074   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7075   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7076   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7077   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7078     if (Mask[i] >= 0 && Mask[i] < Size) {
7079       V1Mask[i] = Mask[i];
7080       BlendMask[i] = i;
7081     } else if (Mask[i] >= Size) {
7082       V2Mask[i] = Mask[i] - Size;
7083       BlendMask[i] = i + Size;
7084     }
7085
7086   // Try to lower with the simpler initial blend strategy unless one of the
7087   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7088   // shuffle may be able to fold with a load or other benefit. However, when
7089   // we'll have to do 2x as many shuffles in order to achieve this, blending
7090   // first is a better strategy.
7091   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7092     if (SDValue BlendPerm =
7093             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7094       return BlendPerm;
7095
7096   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7097   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7098   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7099 }
7100
7101 /// \brief Try to lower a vector shuffle as a byte rotation.
7102 ///
7103 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7104 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7105 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7106 /// try to generically lower a vector shuffle through such an pattern. It
7107 /// does not check for the profitability of lowering either as PALIGNR or
7108 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7109 /// This matches shuffle vectors that look like:
7110 ///
7111 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7112 ///
7113 /// Essentially it concatenates V1 and V2, shifts right by some number of
7114 /// elements, and takes the low elements as the result. Note that while this is
7115 /// specified as a *right shift* because x86 is little-endian, it is a *left
7116 /// rotate* of the vector lanes.
7117 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7118                                               SDValue V2,
7119                                               ArrayRef<int> Mask,
7120                                               const X86Subtarget *Subtarget,
7121                                               SelectionDAG &DAG) {
7122   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7123
7124   int NumElts = Mask.size();
7125   int NumLanes = VT.getSizeInBits() / 128;
7126   int NumLaneElts = NumElts / NumLanes;
7127
7128   // We need to detect various ways of spelling a rotation:
7129   //   [11, 12, 13, 14, 15,  0,  1,  2]
7130   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7131   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7132   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7133   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7134   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7135   int Rotation = 0;
7136   SDValue Lo, Hi;
7137   for (int l = 0; l < NumElts; l += NumLaneElts) {
7138     for (int i = 0; i < NumLaneElts; ++i) {
7139       if (Mask[l + i] == -1)
7140         continue;
7141       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7142
7143       // Get the mod-Size index and lane correct it.
7144       int LaneIdx = (Mask[l + i] % NumElts) - l;
7145       // Make sure it was in this lane.
7146       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7147         return SDValue();
7148
7149       // Determine where a rotated vector would have started.
7150       int StartIdx = i - LaneIdx;
7151       if (StartIdx == 0)
7152         // The identity rotation isn't interesting, stop.
7153         return SDValue();
7154
7155       // If we found the tail of a vector the rotation must be the missing
7156       // front. If we found the head of a vector, it must be how much of the
7157       // head.
7158       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7159
7160       if (Rotation == 0)
7161         Rotation = CandidateRotation;
7162       else if (Rotation != CandidateRotation)
7163         // The rotations don't match, so we can't match this mask.
7164         return SDValue();
7165
7166       // Compute which value this mask is pointing at.
7167       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7168
7169       // Compute which of the two target values this index should be assigned
7170       // to. This reflects whether the high elements are remaining or the low
7171       // elements are remaining.
7172       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7173
7174       // Either set up this value if we've not encountered it before, or check
7175       // that it remains consistent.
7176       if (!TargetV)
7177         TargetV = MaskV;
7178       else if (TargetV != MaskV)
7179         // This may be a rotation, but it pulls from the inputs in some
7180         // unsupported interleaving.
7181         return SDValue();
7182     }
7183   }
7184
7185   // Check that we successfully analyzed the mask, and normalize the results.
7186   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7187   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7188   if (!Lo)
7189     Lo = Hi;
7190   else if (!Hi)
7191     Hi = Lo;
7192
7193   // The actual rotate instruction rotates bytes, so we need to scale the
7194   // rotation based on how many bytes are in the vector lane.
7195   int Scale = 16 / NumLaneElts;
7196
7197   // SSSE3 targets can use the palignr instruction.
7198   if (Subtarget->hasSSSE3()) {
7199     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7200     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7201     Lo = DAG.getBitcast(AlignVT, Lo);
7202     Hi = DAG.getBitcast(AlignVT, Hi);
7203
7204     return DAG.getBitcast(
7205         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7206                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7207   }
7208
7209   assert(VT.getSizeInBits() == 128 &&
7210          "Rotate-based lowering only supports 128-bit lowering!");
7211   assert(Mask.size() <= 16 &&
7212          "Can shuffle at most 16 bytes in a 128-bit vector!");
7213
7214   // Default SSE2 implementation
7215   int LoByteShift = 16 - Rotation * Scale;
7216   int HiByteShift = Rotation * Scale;
7217
7218   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7219   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7220   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7221
7222   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7223                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7224   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7225                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7226   return DAG.getBitcast(VT,
7227                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7228 }
7229
7230 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7231 ///
7232 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7233 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7234 /// matches elements from one of the input vectors shuffled to the left or
7235 /// right with zeroable elements 'shifted in'. It handles both the strictly
7236 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7237 /// quad word lane.
7238 ///
7239 /// PSHL : (little-endian) left bit shift.
7240 /// [ zz, 0, zz,  2 ]
7241 /// [ -1, 4, zz, -1 ]
7242 /// PSRL : (little-endian) right bit shift.
7243 /// [  1, zz,  3, zz]
7244 /// [ -1, -1,  7, zz]
7245 /// PSLLDQ : (little-endian) left byte shift
7246 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7247 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7248 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7249 /// PSRLDQ : (little-endian) right byte shift
7250 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7251 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7252 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7253 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7254                                          SDValue V2, ArrayRef<int> Mask,
7255                                          SelectionDAG &DAG) {
7256   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7257
7258   int Size = Mask.size();
7259   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7260
7261   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7262     for (int i = 0; i < Size; i += Scale)
7263       for (int j = 0; j < Shift; ++j)
7264         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7265           return false;
7266
7267     return true;
7268   };
7269
7270   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7271     for (int i = 0; i != Size; i += Scale) {
7272       unsigned Pos = Left ? i + Shift : i;
7273       unsigned Low = Left ? i : i + Shift;
7274       unsigned Len = Scale - Shift;
7275       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7276                                       Low + (V == V1 ? 0 : Size)))
7277         return SDValue();
7278     }
7279
7280     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7281     bool ByteShift = ShiftEltBits > 64;
7282     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7283                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7284     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7285
7286     // Normalize the scale for byte shifts to still produce an i64 element
7287     // type.
7288     Scale = ByteShift ? Scale / 2 : Scale;
7289
7290     // We need to round trip through the appropriate type for the shift.
7291     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7292     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7293     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7294            "Illegal integer vector type");
7295     V = DAG.getBitcast(ShiftVT, V);
7296
7297     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7298                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7299     return DAG.getBitcast(VT, V);
7300   };
7301
7302   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7303   // keep doubling the size of the integer elements up to that. We can
7304   // then shift the elements of the integer vector by whole multiples of
7305   // their width within the elements of the larger integer vector. Test each
7306   // multiple to see if we can find a match with the moved element indices
7307   // and that the shifted in elements are all zeroable.
7308   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7309     for (int Shift = 1; Shift != Scale; ++Shift)
7310       for (bool Left : {true, false})
7311         if (CheckZeros(Shift, Scale, Left))
7312           for (SDValue V : {V1, V2})
7313             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7314               return Match;
7315
7316   // no match
7317   return SDValue();
7318 }
7319
7320 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7321 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7322                                            SDValue V2, ArrayRef<int> Mask,
7323                                            SelectionDAG &DAG) {
7324   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7325   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7326
7327   int Size = Mask.size();
7328   int HalfSize = Size / 2;
7329   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7330
7331   // Upper half must be undefined.
7332   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7333     return SDValue();
7334
7335   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7336   // Remainder of lower half result is zero and upper half is all undef.
7337   auto LowerAsEXTRQ = [&]() {
7338     // Determine the extraction length from the part of the
7339     // lower half that isn't zeroable.
7340     int Len = HalfSize;
7341     for (; Len > 0; --Len)
7342       if (!Zeroable[Len - 1])
7343         break;
7344     assert(Len > 0 && "Zeroable shuffle mask");
7345
7346     // Attempt to match first Len sequential elements from the lower half.
7347     SDValue Src;
7348     int Idx = -1;
7349     for (int i = 0; i != Len; ++i) {
7350       int M = Mask[i];
7351       if (M < 0)
7352         continue;
7353       SDValue &V = (M < Size ? V1 : V2);
7354       M = M % Size;
7355
7356       // All mask elements must be in the lower half.
7357       if (M >= HalfSize)
7358         return SDValue();
7359
7360       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7361         Src = V;
7362         Idx = M - i;
7363         continue;
7364       }
7365       return SDValue();
7366     }
7367
7368     if (Idx < 0)
7369       return SDValue();
7370
7371     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7372     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7373     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7374     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7375                        DAG.getConstant(BitLen, DL, MVT::i8),
7376                        DAG.getConstant(BitIdx, DL, MVT::i8));
7377   };
7378
7379   if (SDValue ExtrQ = LowerAsEXTRQ())
7380     return ExtrQ;
7381
7382   // INSERTQ: Extract lowest Len elements from lower half of second source and
7383   // insert over first source, starting at Idx.
7384   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7385   auto LowerAsInsertQ = [&]() {
7386     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7387       SDValue Base;
7388
7389       // Attempt to match first source from mask before insertion point.
7390       if (isUndefInRange(Mask, 0, Idx)) {
7391         /* EMPTY */
7392       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7393         Base = V1;
7394       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7395         Base = V2;
7396       } else {
7397         continue;
7398       }
7399
7400       // Extend the extraction length looking to match both the insertion of
7401       // the second source and the remaining elements of the first.
7402       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7403         SDValue Insert;
7404         int Len = Hi - Idx;
7405
7406         // Match insertion.
7407         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7408           Insert = V1;
7409         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7410           Insert = V2;
7411         } else {
7412           continue;
7413         }
7414
7415         // Match the remaining elements of the lower half.
7416         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7417           /* EMPTY */
7418         } else if ((!Base || (Base == V1)) &&
7419                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7420           Base = V1;
7421         } else if ((!Base || (Base == V2)) &&
7422                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7423                                               Size + Hi)) {
7424           Base = V2;
7425         } else {
7426           continue;
7427         }
7428
7429         // We may not have a base (first source) - this can safely be undefined.
7430         if (!Base)
7431           Base = DAG.getUNDEF(VT);
7432
7433         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7434         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7435         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7436                            DAG.getConstant(BitLen, DL, MVT::i8),
7437                            DAG.getConstant(BitIdx, DL, MVT::i8));
7438       }
7439     }
7440
7441     return SDValue();
7442   };
7443
7444   if (SDValue InsertQ = LowerAsInsertQ())
7445     return InsertQ;
7446
7447   return SDValue();
7448 }
7449
7450 /// \brief Lower a vector shuffle as a zero or any extension.
7451 ///
7452 /// Given a specific number of elements, element bit width, and extension
7453 /// stride, produce either a zero or any extension based on the available
7454 /// features of the subtarget. The extended elements are consecutive and
7455 /// begin and can start from an offseted element index in the input; to
7456 /// avoid excess shuffling the offset must either being in the bottom lane
7457 /// or at the start of a higher lane. All extended elements must be from
7458 /// the same lane.
7459 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7460     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7461     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7462   assert(Scale > 1 && "Need a scale to extend.");
7463   int EltBits = VT.getScalarSizeInBits();
7464   int NumElements = VT.getVectorNumElements();
7465   int NumEltsPerLane = 128 / EltBits;
7466   int OffsetLane = Offset / NumEltsPerLane;
7467   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7468          "Only 8, 16, and 32 bit elements can be extended.");
7469   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7470   assert(0 <= Offset && "Extension offset must be positive.");
7471   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7472          "Extension offset must be in the first lane or start an upper lane.");
7473
7474   // Check that an index is in same lane as the base offset.
7475   auto SafeOffset = [&](int Idx) {
7476     return OffsetLane == (Idx / NumEltsPerLane);
7477   };
7478
7479   // Shift along an input so that the offset base moves to the first element.
7480   auto ShuffleOffset = [&](SDValue V) {
7481     if (!Offset)
7482       return V;
7483
7484     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7485     for (int i = 0; i * Scale < NumElements; ++i) {
7486       int SrcIdx = i + Offset;
7487       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7488     }
7489     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7490   };
7491
7492   // Found a valid zext mask! Try various lowering strategies based on the
7493   // input type and available ISA extensions.
7494   if (Subtarget->hasSSE41()) {
7495     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7496     // PUNPCK will catch this in a later shuffle match.
7497     if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7498       return SDValue();
7499     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7500                                  NumElements / Scale);
7501     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7502     return DAG.getBitcast(VT, InputV);
7503   }
7504
7505   assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7506
7507   // For any extends we can cheat for larger element sizes and use shuffle
7508   // instructions that can fold with a load and/or copy.
7509   if (AnyExt && EltBits == 32) {
7510     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7511                          -1};
7512     return DAG.getBitcast(
7513         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7514                         DAG.getBitcast(MVT::v4i32, InputV),
7515                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7516   }
7517   if (AnyExt && EltBits == 16 && Scale > 2) {
7518     int PSHUFDMask[4] = {Offset / 2, -1,
7519                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7520     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7521                          DAG.getBitcast(MVT::v4i32, InputV),
7522                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7523     int PSHUFWMask[4] = {1, -1, -1, -1};
7524     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7525     return DAG.getBitcast(
7526         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7527                         DAG.getBitcast(MVT::v8i16, InputV),
7528                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7529   }
7530
7531   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7532   // to 64-bits.
7533   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7534     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7535     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7536
7537     int LoIdx = Offset * EltBits;
7538     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7539                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7540                                          DAG.getConstant(EltBits, DL, MVT::i8),
7541                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7542
7543     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7544         !SafeOffset(Offset + 1))
7545       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7546
7547     int HiIdx = (Offset + 1) * EltBits;
7548     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7549                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7550                                          DAG.getConstant(EltBits, DL, MVT::i8),
7551                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7552     return DAG.getNode(ISD::BITCAST, DL, VT,
7553                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7554   }
7555
7556   // If this would require more than 2 unpack instructions to expand, use
7557   // pshufb when available. We can only use more than 2 unpack instructions
7558   // when zero extending i8 elements which also makes it easier to use pshufb.
7559   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7560     assert(NumElements == 16 && "Unexpected byte vector width!");
7561     SDValue PSHUFBMask[16];
7562     for (int i = 0; i < 16; ++i) {
7563       int Idx = Offset + (i / Scale);
7564       PSHUFBMask[i] = DAG.getConstant(
7565           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7566     }
7567     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7568     return DAG.getBitcast(VT,
7569                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7570                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7571                                                   MVT::v16i8, PSHUFBMask)));
7572   }
7573
7574   // If we are extending from an offset, ensure we start on a boundary that
7575   // we can unpack from.
7576   int AlignToUnpack = Offset % (NumElements / Scale);
7577   if (AlignToUnpack) {
7578     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7579     for (int i = AlignToUnpack; i < NumElements; ++i)
7580       ShMask[i - AlignToUnpack] = i;
7581     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7582     Offset -= AlignToUnpack;
7583   }
7584
7585   // Otherwise emit a sequence of unpacks.
7586   do {
7587     unsigned UnpackLoHi = X86ISD::UNPCKL;
7588     if (Offset >= (NumElements / 2)) {
7589       UnpackLoHi = X86ISD::UNPCKH;
7590       Offset -= (NumElements / 2);
7591     }
7592
7593     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7594     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7595                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7596     InputV = DAG.getBitcast(InputVT, InputV);
7597     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7598     Scale /= 2;
7599     EltBits *= 2;
7600     NumElements /= 2;
7601   } while (Scale > 1);
7602   return DAG.getBitcast(VT, InputV);
7603 }
7604
7605 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7606 ///
7607 /// This routine will try to do everything in its power to cleverly lower
7608 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7609 /// check for the profitability of this lowering,  it tries to aggressively
7610 /// match this pattern. It will use all of the micro-architectural details it
7611 /// can to emit an efficient lowering. It handles both blends with all-zero
7612 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7613 /// masking out later).
7614 ///
7615 /// The reason we have dedicated lowering for zext-style shuffles is that they
7616 /// are both incredibly common and often quite performance sensitive.
7617 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7618     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7619     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7620   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7621
7622   int Bits = VT.getSizeInBits();
7623   int NumLanes = Bits / 128;
7624   int NumElements = VT.getVectorNumElements();
7625   int NumEltsPerLane = NumElements / NumLanes;
7626   assert(VT.getScalarSizeInBits() <= 32 &&
7627          "Exceeds 32-bit integer zero extension limit");
7628   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7629
7630   // Define a helper function to check a particular ext-scale and lower to it if
7631   // valid.
7632   auto Lower = [&](int Scale) -> SDValue {
7633     SDValue InputV;
7634     bool AnyExt = true;
7635     int Offset = 0;
7636     int Matches = 0;
7637     for (int i = 0; i < NumElements; ++i) {
7638       int M = Mask[i];
7639       if (M == -1)
7640         continue; // Valid anywhere but doesn't tell us anything.
7641       if (i % Scale != 0) {
7642         // Each of the extended elements need to be zeroable.
7643         if (!Zeroable[i])
7644           return SDValue();
7645
7646         // We no longer are in the anyext case.
7647         AnyExt = false;
7648         continue;
7649       }
7650
7651       // Each of the base elements needs to be consecutive indices into the
7652       // same input vector.
7653       SDValue V = M < NumElements ? V1 : V2;
7654       M = M % NumElements;
7655       if (!InputV) {
7656         InputV = V;
7657         Offset = M - (i / Scale);
7658       } else if (InputV != V)
7659         return SDValue(); // Flip-flopping inputs.
7660
7661       // Offset must start in the lowest 128-bit lane or at the start of an
7662       // upper lane.
7663       // FIXME: Is it ever worth allowing a negative base offset?
7664       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7665             (Offset % NumEltsPerLane) == 0))
7666         return SDValue();
7667
7668       // If we are offsetting, all referenced entries must come from the same
7669       // lane.
7670       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7671         return SDValue();
7672
7673       if ((M % NumElements) != (Offset + (i / Scale)))
7674         return SDValue(); // Non-consecutive strided elements.
7675       Matches++;
7676     }
7677
7678     // If we fail to find an input, we have a zero-shuffle which should always
7679     // have already been handled.
7680     // FIXME: Maybe handle this here in case during blending we end up with one?
7681     if (!InputV)
7682       return SDValue();
7683
7684     // If we are offsetting, don't extend if we only match a single input, we
7685     // can always do better by using a basic PSHUF or PUNPCK.
7686     if (Offset != 0 && Matches < 2)
7687       return SDValue();
7688
7689     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7690         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7691   };
7692
7693   // The widest scale possible for extending is to a 64-bit integer.
7694   assert(Bits % 64 == 0 &&
7695          "The number of bits in a vector must be divisible by 64 on x86!");
7696   int NumExtElements = Bits / 64;
7697
7698   // Each iteration, try extending the elements half as much, but into twice as
7699   // many elements.
7700   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7701     assert(NumElements % NumExtElements == 0 &&
7702            "The input vector size must be divisible by the extended size.");
7703     if (SDValue V = Lower(NumElements / NumExtElements))
7704       return V;
7705   }
7706
7707   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7708   if (Bits != 128)
7709     return SDValue();
7710
7711   // Returns one of the source operands if the shuffle can be reduced to a
7712   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7713   auto CanZExtLowHalf = [&]() {
7714     for (int i = NumElements / 2; i != NumElements; ++i)
7715       if (!Zeroable[i])
7716         return SDValue();
7717     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7718       return V1;
7719     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7720       return V2;
7721     return SDValue();
7722   };
7723
7724   if (SDValue V = CanZExtLowHalf()) {
7725     V = DAG.getBitcast(MVT::v2i64, V);
7726     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7727     return DAG.getBitcast(VT, V);
7728   }
7729
7730   // No viable ext lowering found.
7731   return SDValue();
7732 }
7733
7734 /// \brief Try to get a scalar value for a specific element of a vector.
7735 ///
7736 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7737 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7738                                               SelectionDAG &DAG) {
7739   MVT VT = V.getSimpleValueType();
7740   MVT EltVT = VT.getVectorElementType();
7741   while (V.getOpcode() == ISD::BITCAST)
7742     V = V.getOperand(0);
7743   // If the bitcasts shift the element size, we can't extract an equivalent
7744   // element from it.
7745   MVT NewVT = V.getSimpleValueType();
7746   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7747     return SDValue();
7748
7749   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7750       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7751     // Ensure the scalar operand is the same size as the destination.
7752     // FIXME: Add support for scalar truncation where possible.
7753     SDValue S = V.getOperand(Idx);
7754     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7755       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7756   }
7757
7758   return SDValue();
7759 }
7760
7761 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7762 ///
7763 /// This is particularly important because the set of instructions varies
7764 /// significantly based on whether the operand is a load or not.
7765 static bool isShuffleFoldableLoad(SDValue V) {
7766   while (V.getOpcode() == ISD::BITCAST)
7767     V = V.getOperand(0);
7768
7769   return ISD::isNON_EXTLoad(V.getNode());
7770 }
7771
7772 /// \brief Try to lower insertion of a single element into a zero vector.
7773 ///
7774 /// This is a common pattern that we have especially efficient patterns to lower
7775 /// across all subtarget feature sets.
7776 static SDValue lowerVectorShuffleAsElementInsertion(
7777     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7778     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7779   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7780   MVT ExtVT = VT;
7781   MVT EltVT = VT.getVectorElementType();
7782
7783   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7784                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7785                 Mask.begin();
7786   bool IsV1Zeroable = true;
7787   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7788     if (i != V2Index && !Zeroable[i]) {
7789       IsV1Zeroable = false;
7790       break;
7791     }
7792
7793   // Check for a single input from a SCALAR_TO_VECTOR node.
7794   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7795   // all the smarts here sunk into that routine. However, the current
7796   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7797   // vector shuffle lowering is dead.
7798   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7799                                                DAG);
7800   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7801     // We need to zext the scalar if it is smaller than an i32.
7802     V2S = DAG.getBitcast(EltVT, V2S);
7803     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7804       // Using zext to expand a narrow element won't work for non-zero
7805       // insertions.
7806       if (!IsV1Zeroable)
7807         return SDValue();
7808
7809       // Zero-extend directly to i32.
7810       ExtVT = MVT::v4i32;
7811       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7812     }
7813     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7814   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7815              EltVT == MVT::i16) {
7816     // Either not inserting from the low element of the input or the input
7817     // element size is too small to use VZEXT_MOVL to clear the high bits.
7818     return SDValue();
7819   }
7820
7821   if (!IsV1Zeroable) {
7822     // If V1 can't be treated as a zero vector we have fewer options to lower
7823     // this. We can't support integer vectors or non-zero targets cheaply, and
7824     // the V1 elements can't be permuted in any way.
7825     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7826     if (!VT.isFloatingPoint() || V2Index != 0)
7827       return SDValue();
7828     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7829     V1Mask[V2Index] = -1;
7830     if (!isNoopShuffleMask(V1Mask))
7831       return SDValue();
7832     // This is essentially a special case blend operation, but if we have
7833     // general purpose blend operations, they are always faster. Bail and let
7834     // the rest of the lowering handle these as blends.
7835     if (Subtarget->hasSSE41())
7836       return SDValue();
7837
7838     // Otherwise, use MOVSD or MOVSS.
7839     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7840            "Only two types of floating point element types to handle!");
7841     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7842                        ExtVT, V1, V2);
7843   }
7844
7845   // This lowering only works for the low element with floating point vectors.
7846   if (VT.isFloatingPoint() && V2Index != 0)
7847     return SDValue();
7848
7849   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7850   if (ExtVT != VT)
7851     V2 = DAG.getBitcast(VT, V2);
7852
7853   if (V2Index != 0) {
7854     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7855     // the desired position. Otherwise it is more efficient to do a vector
7856     // shift left. We know that we can do a vector shift left because all
7857     // the inputs are zero.
7858     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7859       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7860       V2Shuffle[V2Index] = 0;
7861       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7862     } else {
7863       V2 = DAG.getBitcast(MVT::v2i64, V2);
7864       V2 = DAG.getNode(
7865           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7866           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7867                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7868                               DAG.getDataLayout(), VT)));
7869       V2 = DAG.getBitcast(VT, V2);
7870     }
7871   }
7872   return V2;
7873 }
7874
7875 /// \brief Try to lower broadcast of a single element.
7876 ///
7877 /// For convenience, this code also bundles all of the subtarget feature set
7878 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7879 /// a convenient way to factor it out.
7880 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7881                                              ArrayRef<int> Mask,
7882                                              const X86Subtarget *Subtarget,
7883                                              SelectionDAG &DAG) {
7884   if (!Subtarget->hasAVX())
7885     return SDValue();
7886   if (VT.isInteger() && !Subtarget->hasAVX2())
7887     return SDValue();
7888
7889   // Check that the mask is a broadcast.
7890   int BroadcastIdx = -1;
7891   for (int M : Mask)
7892     if (M >= 0 && BroadcastIdx == -1)
7893       BroadcastIdx = M;
7894     else if (M >= 0 && M != BroadcastIdx)
7895       return SDValue();
7896
7897   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7898                                             "a sorted mask where the broadcast "
7899                                             "comes from V1.");
7900
7901   // Go up the chain of (vector) values to find a scalar load that we can
7902   // combine with the broadcast.
7903   for (;;) {
7904     switch (V.getOpcode()) {
7905     case ISD::CONCAT_VECTORS: {
7906       int OperandSize = Mask.size() / V.getNumOperands();
7907       V = V.getOperand(BroadcastIdx / OperandSize);
7908       BroadcastIdx %= OperandSize;
7909       continue;
7910     }
7911
7912     case ISD::INSERT_SUBVECTOR: {
7913       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7914       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7915       if (!ConstantIdx)
7916         break;
7917
7918       int BeginIdx = (int)ConstantIdx->getZExtValue();
7919       int EndIdx =
7920           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7921       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7922         BroadcastIdx -= BeginIdx;
7923         V = VInner;
7924       } else {
7925         V = VOuter;
7926       }
7927       continue;
7928     }
7929     }
7930     break;
7931   }
7932
7933   // Check if this is a broadcast of a scalar. We special case lowering
7934   // for scalars so that we can more effectively fold with loads.
7935   // First, look through bitcast: if the original value has a larger element
7936   // type than the shuffle, the broadcast element is in essence truncated.
7937   // Make that explicit to ease folding.
7938   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7939     EVT EltVT = VT.getVectorElementType();
7940     SDValue V0 = V.getOperand(0);
7941     EVT V0VT = V0.getValueType();
7942
7943     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7944         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7945          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7946       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7947       BroadcastIdx = 0;
7948     }
7949   }
7950
7951   // Also check the simpler case, where we can directly reuse the scalar.
7952   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7953       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7954     V = V.getOperand(BroadcastIdx);
7955
7956     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7957     // Only AVX2 has register broadcasts.
7958     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7959       return SDValue();
7960   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7961     // We can't broadcast from a vector register without AVX2, and we can only
7962     // broadcast from the zero-element of a vector register.
7963     return SDValue();
7964   }
7965
7966   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7967 }
7968
7969 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7970 // INSERTPS when the V1 elements are already in the correct locations
7971 // because otherwise we can just always use two SHUFPS instructions which
7972 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7973 // perform INSERTPS if a single V1 element is out of place and all V2
7974 // elements are zeroable.
7975 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7976                                             ArrayRef<int> Mask,
7977                                             SelectionDAG &DAG) {
7978   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7979   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7980   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7981   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7982
7983   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7984
7985   unsigned ZMask = 0;
7986   int V1DstIndex = -1;
7987   int V2DstIndex = -1;
7988   bool V1UsedInPlace = false;
7989
7990   for (int i = 0; i < 4; ++i) {
7991     // Synthesize a zero mask from the zeroable elements (includes undefs).
7992     if (Zeroable[i]) {
7993       ZMask |= 1 << i;
7994       continue;
7995     }
7996
7997     // Flag if we use any V1 inputs in place.
7998     if (i == Mask[i]) {
7999       V1UsedInPlace = true;
8000       continue;
8001     }
8002
8003     // We can only insert a single non-zeroable element.
8004     if (V1DstIndex != -1 || V2DstIndex != -1)
8005       return SDValue();
8006
8007     if (Mask[i] < 4) {
8008       // V1 input out of place for insertion.
8009       V1DstIndex = i;
8010     } else {
8011       // V2 input for insertion.
8012       V2DstIndex = i;
8013     }
8014   }
8015
8016   // Don't bother if we have no (non-zeroable) element for insertion.
8017   if (V1DstIndex == -1 && V2DstIndex == -1)
8018     return SDValue();
8019
8020   // Determine element insertion src/dst indices. The src index is from the
8021   // start of the inserted vector, not the start of the concatenated vector.
8022   unsigned V2SrcIndex = 0;
8023   if (V1DstIndex != -1) {
8024     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8025     // and don't use the original V2 at all.
8026     V2SrcIndex = Mask[V1DstIndex];
8027     V2DstIndex = V1DstIndex;
8028     V2 = V1;
8029   } else {
8030     V2SrcIndex = Mask[V2DstIndex] - 4;
8031   }
8032
8033   // If no V1 inputs are used in place, then the result is created only from
8034   // the zero mask and the V2 insertion - so remove V1 dependency.
8035   if (!V1UsedInPlace)
8036     V1 = DAG.getUNDEF(MVT::v4f32);
8037
8038   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8039   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8040
8041   // Insert the V2 element into the desired position.
8042   SDLoc DL(Op);
8043   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8044                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8045 }
8046
8047 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8048 /// UNPCK instruction.
8049 ///
8050 /// This specifically targets cases where we end up with alternating between
8051 /// the two inputs, and so can permute them into something that feeds a single
8052 /// UNPCK instruction. Note that this routine only targets integer vectors
8053 /// because for floating point vectors we have a generalized SHUFPS lowering
8054 /// strategy that handles everything that doesn't *exactly* match an unpack,
8055 /// making this clever lowering unnecessary.
8056 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8057                                                     SDValue V1, SDValue V2,
8058                                                     ArrayRef<int> Mask,
8059                                                     SelectionDAG &DAG) {
8060   assert(!VT.isFloatingPoint() &&
8061          "This routine only supports integer vectors.");
8062   assert(!isSingleInputShuffleMask(Mask) &&
8063          "This routine should only be used when blending two inputs.");
8064   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8065
8066   int Size = Mask.size();
8067
8068   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8069     return M >= 0 && M % Size < Size / 2;
8070   });
8071   int NumHiInputs = std::count_if(
8072       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8073
8074   bool UnpackLo = NumLoInputs >= NumHiInputs;
8075
8076   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8077     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8078     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8079
8080     for (int i = 0; i < Size; ++i) {
8081       if (Mask[i] < 0)
8082         continue;
8083
8084       // Each element of the unpack contains Scale elements from this mask.
8085       int UnpackIdx = i / Scale;
8086
8087       // We only handle the case where V1 feeds the first slots of the unpack.
8088       // We rely on canonicalization to ensure this is the case.
8089       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8090         return SDValue();
8091
8092       // Setup the mask for this input. The indexing is tricky as we have to
8093       // handle the unpack stride.
8094       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8095       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8096           Mask[i] % Size;
8097     }
8098
8099     // If we will have to shuffle both inputs to use the unpack, check whether
8100     // we can just unpack first and shuffle the result. If so, skip this unpack.
8101     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8102         !isNoopShuffleMask(V2Mask))
8103       return SDValue();
8104
8105     // Shuffle the inputs into place.
8106     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8107     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8108
8109     // Cast the inputs to the type we will use to unpack them.
8110     V1 = DAG.getBitcast(UnpackVT, V1);
8111     V2 = DAG.getBitcast(UnpackVT, V2);
8112
8113     // Unpack the inputs and cast the result back to the desired type.
8114     return DAG.getBitcast(
8115         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8116                         UnpackVT, V1, V2));
8117   };
8118
8119   // We try each unpack from the largest to the smallest to try and find one
8120   // that fits this mask.
8121   int OrigNumElements = VT.getVectorNumElements();
8122   int OrigScalarSize = VT.getScalarSizeInBits();
8123   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8124     int Scale = ScalarSize / OrigScalarSize;
8125     int NumElements = OrigNumElements / Scale;
8126     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8127     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8128       return Unpack;
8129   }
8130
8131   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8132   // initial unpack.
8133   if (NumLoInputs == 0 || NumHiInputs == 0) {
8134     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8135            "We have to have *some* inputs!");
8136     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8137
8138     // FIXME: We could consider the total complexity of the permute of each
8139     // possible unpacking. Or at the least we should consider how many
8140     // half-crossings are created.
8141     // FIXME: We could consider commuting the unpacks.
8142
8143     SmallVector<int, 32> PermMask;
8144     PermMask.assign(Size, -1);
8145     for (int i = 0; i < Size; ++i) {
8146       if (Mask[i] < 0)
8147         continue;
8148
8149       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8150
8151       PermMask[i] =
8152           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8153     }
8154     return DAG.getVectorShuffle(
8155         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8156                             DL, VT, V1, V2),
8157         DAG.getUNDEF(VT), PermMask);
8158   }
8159
8160   return SDValue();
8161 }
8162
8163 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8164 ///
8165 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8166 /// support for floating point shuffles but not integer shuffles. These
8167 /// instructions will incur a domain crossing penalty on some chips though so
8168 /// it is better to avoid lowering through this for integer vectors where
8169 /// possible.
8170 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8171                                        const X86Subtarget *Subtarget,
8172                                        SelectionDAG &DAG) {
8173   SDLoc DL(Op);
8174   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8175   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8176   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8177   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8178   ArrayRef<int> Mask = SVOp->getMask();
8179   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8180
8181   if (isSingleInputShuffleMask(Mask)) {
8182     // Use low duplicate instructions for masks that match their pattern.
8183     if (Subtarget->hasSSE3())
8184       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8185         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8186
8187     // Straight shuffle of a single input vector. Simulate this by using the
8188     // single input as both of the "inputs" to this instruction..
8189     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8190
8191     if (Subtarget->hasAVX()) {
8192       // If we have AVX, we can use VPERMILPS which will allow folding a load
8193       // into the shuffle.
8194       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8195                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8196     }
8197
8198     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8199                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8200   }
8201   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8202   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8203
8204   // If we have a single input, insert that into V1 if we can do so cheaply.
8205   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8206     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8207             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8208       return Insertion;
8209     // Try inverting the insertion since for v2 masks it is easy to do and we
8210     // can't reliably sort the mask one way or the other.
8211     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8212                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8213     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8214             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8215       return Insertion;
8216   }
8217
8218   // Try to use one of the special instruction patterns to handle two common
8219   // blend patterns if a zero-blend above didn't work.
8220   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8221       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8222     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8223       // We can either use a special instruction to load over the low double or
8224       // to move just the low double.
8225       return DAG.getNode(
8226           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8227           DL, MVT::v2f64, V2,
8228           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8229
8230   if (Subtarget->hasSSE41())
8231     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8232                                                   Subtarget, DAG))
8233       return Blend;
8234
8235   // Use dedicated unpack instructions for masks that match their pattern.
8236   if (SDValue V =
8237           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8238     return V;
8239
8240   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8241   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8242                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8243 }
8244
8245 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8246 ///
8247 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8248 /// the integer unit to minimize domain crossing penalties. However, for blends
8249 /// it falls back to the floating point shuffle operation with appropriate bit
8250 /// casting.
8251 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8252                                        const X86Subtarget *Subtarget,
8253                                        SelectionDAG &DAG) {
8254   SDLoc DL(Op);
8255   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8256   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8257   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8258   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8259   ArrayRef<int> Mask = SVOp->getMask();
8260   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8261
8262   if (isSingleInputShuffleMask(Mask)) {
8263     // Check for being able to broadcast a single element.
8264     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8265                                                           Mask, Subtarget, DAG))
8266       return Broadcast;
8267
8268     // Straight shuffle of a single input vector. For everything from SSE2
8269     // onward this has a single fast instruction with no scary immediates.
8270     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8271     V1 = DAG.getBitcast(MVT::v4i32, V1);
8272     int WidenedMask[4] = {
8273         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8274         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8275     return DAG.getBitcast(
8276         MVT::v2i64,
8277         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8278                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8279   }
8280   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8281   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8282   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8283   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8284
8285   // If we have a blend of two PACKUS operations an the blend aligns with the
8286   // low and half halves, we can just merge the PACKUS operations. This is
8287   // particularly important as it lets us merge shuffles that this routine itself
8288   // creates.
8289   auto GetPackNode = [](SDValue V) {
8290     while (V.getOpcode() == ISD::BITCAST)
8291       V = V.getOperand(0);
8292
8293     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8294   };
8295   if (SDValue V1Pack = GetPackNode(V1))
8296     if (SDValue V2Pack = GetPackNode(V2))
8297       return DAG.getBitcast(MVT::v2i64,
8298                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8299                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8300                                                      : V1Pack.getOperand(1),
8301                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8302                                                      : V2Pack.getOperand(1)));
8303
8304   // Try to use shift instructions.
8305   if (SDValue Shift =
8306           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8307     return Shift;
8308
8309   // When loading a scalar and then shuffling it into a vector we can often do
8310   // the insertion cheaply.
8311   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8312           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8313     return Insertion;
8314   // Try inverting the insertion since for v2 masks it is easy to do and we
8315   // can't reliably sort the mask one way or the other.
8316   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8317   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8318           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8319     return Insertion;
8320
8321   // We have different paths for blend lowering, but they all must use the
8322   // *exact* same predicate.
8323   bool IsBlendSupported = Subtarget->hasSSE41();
8324   if (IsBlendSupported)
8325     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8326                                                   Subtarget, DAG))
8327       return Blend;
8328
8329   // Use dedicated unpack instructions for masks that match their pattern.
8330   if (SDValue V =
8331           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8332     return V;
8333
8334   // Try to use byte rotation instructions.
8335   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8336   if (Subtarget->hasSSSE3())
8337     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8338             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8339       return Rotate;
8340
8341   // If we have direct support for blends, we should lower by decomposing into
8342   // a permute. That will be faster than the domain cross.
8343   if (IsBlendSupported)
8344     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8345                                                       Mask, DAG);
8346
8347   // We implement this with SHUFPD which is pretty lame because it will likely
8348   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8349   // However, all the alternatives are still more cycles and newer chips don't
8350   // have this problem. It would be really nice if x86 had better shuffles here.
8351   V1 = DAG.getBitcast(MVT::v2f64, V1);
8352   V2 = DAG.getBitcast(MVT::v2f64, V2);
8353   return DAG.getBitcast(MVT::v2i64,
8354                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8355 }
8356
8357 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8358 ///
8359 /// This is used to disable more specialized lowerings when the shufps lowering
8360 /// will happen to be efficient.
8361 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8362   // This routine only handles 128-bit shufps.
8363   assert(Mask.size() == 4 && "Unsupported mask size!");
8364
8365   // To lower with a single SHUFPS we need to have the low half and high half
8366   // each requiring a single input.
8367   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8368     return false;
8369   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8370     return false;
8371
8372   return true;
8373 }
8374
8375 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8376 ///
8377 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8378 /// It makes no assumptions about whether this is the *best* lowering, it simply
8379 /// uses it.
8380 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8381                                             ArrayRef<int> Mask, SDValue V1,
8382                                             SDValue V2, SelectionDAG &DAG) {
8383   SDValue LowV = V1, HighV = V2;
8384   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8385
8386   int NumV2Elements =
8387       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8388
8389   if (NumV2Elements == 1) {
8390     int V2Index =
8391         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8392         Mask.begin();
8393
8394     // Compute the index adjacent to V2Index and in the same half by toggling
8395     // the low bit.
8396     int V2AdjIndex = V2Index ^ 1;
8397
8398     if (Mask[V2AdjIndex] == -1) {
8399       // Handles all the cases where we have a single V2 element and an undef.
8400       // This will only ever happen in the high lanes because we commute the
8401       // vector otherwise.
8402       if (V2Index < 2)
8403         std::swap(LowV, HighV);
8404       NewMask[V2Index] -= 4;
8405     } else {
8406       // Handle the case where the V2 element ends up adjacent to a V1 element.
8407       // To make this work, blend them together as the first step.
8408       int V1Index = V2AdjIndex;
8409       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8410       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8411                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8412
8413       // Now proceed to reconstruct the final blend as we have the necessary
8414       // high or low half formed.
8415       if (V2Index < 2) {
8416         LowV = V2;
8417         HighV = V1;
8418       } else {
8419         HighV = V2;
8420       }
8421       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8422       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8423     }
8424   } else if (NumV2Elements == 2) {
8425     if (Mask[0] < 4 && Mask[1] < 4) {
8426       // Handle the easy case where we have V1 in the low lanes and V2 in the
8427       // high lanes.
8428       NewMask[2] -= 4;
8429       NewMask[3] -= 4;
8430     } else if (Mask[2] < 4 && Mask[3] < 4) {
8431       // We also handle the reversed case because this utility may get called
8432       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8433       // arrange things in the right direction.
8434       NewMask[0] -= 4;
8435       NewMask[1] -= 4;
8436       HighV = V1;
8437       LowV = V2;
8438     } else {
8439       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8440       // trying to place elements directly, just blend them and set up the final
8441       // shuffle to place them.
8442
8443       // The first two blend mask elements are for V1, the second two are for
8444       // V2.
8445       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8446                           Mask[2] < 4 ? Mask[2] : Mask[3],
8447                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8448                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8449       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8450                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8451
8452       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8453       // a blend.
8454       LowV = HighV = V1;
8455       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8456       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8457       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8458       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8459     }
8460   }
8461   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8462                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8463 }
8464
8465 /// \brief Lower 4-lane 32-bit floating point shuffles.
8466 ///
8467 /// Uses instructions exclusively from the floating point unit to minimize
8468 /// domain crossing penalties, as these are sufficient to implement all v4f32
8469 /// shuffles.
8470 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8471                                        const X86Subtarget *Subtarget,
8472                                        SelectionDAG &DAG) {
8473   SDLoc DL(Op);
8474   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8475   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8476   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8477   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8478   ArrayRef<int> Mask = SVOp->getMask();
8479   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8480
8481   int NumV2Elements =
8482       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8483
8484   if (NumV2Elements == 0) {
8485     // Check for being able to broadcast a single element.
8486     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8487                                                           Mask, Subtarget, DAG))
8488       return Broadcast;
8489
8490     // Use even/odd duplicate instructions for masks that match their pattern.
8491     if (Subtarget->hasSSE3()) {
8492       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8493         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8494       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8495         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8496     }
8497
8498     if (Subtarget->hasAVX()) {
8499       // If we have AVX, we can use VPERMILPS which will allow folding a load
8500       // into the shuffle.
8501       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8502                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8503     }
8504
8505     // Otherwise, use a straight shuffle of a single input vector. We pass the
8506     // input vector to both operands to simulate this with a SHUFPS.
8507     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8508                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8509   }
8510
8511   // There are special ways we can lower some single-element blends. However, we
8512   // have custom ways we can lower more complex single-element blends below that
8513   // we defer to if both this and BLENDPS fail to match, so restrict this to
8514   // when the V2 input is targeting element 0 of the mask -- that is the fast
8515   // case here.
8516   if (NumV2Elements == 1 && Mask[0] >= 4)
8517     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8518                                                          Mask, Subtarget, DAG))
8519       return V;
8520
8521   if (Subtarget->hasSSE41()) {
8522     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8523                                                   Subtarget, DAG))
8524       return Blend;
8525
8526     // Use INSERTPS if we can complete the shuffle efficiently.
8527     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8528       return V;
8529
8530     if (!isSingleSHUFPSMask(Mask))
8531       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8532               DL, MVT::v4f32, V1, V2, Mask, DAG))
8533         return BlendPerm;
8534   }
8535
8536   // Use dedicated unpack instructions for masks that match their pattern.
8537   if (SDValue V =
8538           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8539     return V;
8540
8541   // Otherwise fall back to a SHUFPS lowering strategy.
8542   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8543 }
8544
8545 /// \brief Lower 4-lane i32 vector shuffles.
8546 ///
8547 /// We try to handle these with integer-domain shuffles where we can, but for
8548 /// blends we use the floating point domain blend instructions.
8549 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8550                                        const X86Subtarget *Subtarget,
8551                                        SelectionDAG &DAG) {
8552   SDLoc DL(Op);
8553   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8554   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8555   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8556   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8557   ArrayRef<int> Mask = SVOp->getMask();
8558   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8559
8560   // Whenever we can lower this as a zext, that instruction is strictly faster
8561   // than any alternative. It also allows us to fold memory operands into the
8562   // shuffle in many cases.
8563   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8564                                                          Mask, Subtarget, DAG))
8565     return ZExt;
8566
8567   int NumV2Elements =
8568       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8569
8570   if (NumV2Elements == 0) {
8571     // Check for being able to broadcast a single element.
8572     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8573                                                           Mask, Subtarget, DAG))
8574       return Broadcast;
8575
8576     // Straight shuffle of a single input vector. For everything from SSE2
8577     // onward this has a single fast instruction with no scary immediates.
8578     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8579     // but we aren't actually going to use the UNPCK instruction because doing
8580     // so prevents folding a load into this instruction or making a copy.
8581     const int UnpackLoMask[] = {0, 0, 1, 1};
8582     const int UnpackHiMask[] = {2, 2, 3, 3};
8583     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8584       Mask = UnpackLoMask;
8585     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8586       Mask = UnpackHiMask;
8587
8588     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8589                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8590   }
8591
8592   // Try to use shift instructions.
8593   if (SDValue Shift =
8594           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8595     return Shift;
8596
8597   // There are special ways we can lower some single-element blends.
8598   if (NumV2Elements == 1)
8599     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8600                                                          Mask, Subtarget, DAG))
8601       return V;
8602
8603   // We have different paths for blend lowering, but they all must use the
8604   // *exact* same predicate.
8605   bool IsBlendSupported = Subtarget->hasSSE41();
8606   if (IsBlendSupported)
8607     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8608                                                   Subtarget, DAG))
8609       return Blend;
8610
8611   if (SDValue Masked =
8612           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8613     return Masked;
8614
8615   // Use dedicated unpack instructions for masks that match their pattern.
8616   if (SDValue V =
8617           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8618     return V;
8619
8620   // Try to use byte rotation instructions.
8621   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8622   if (Subtarget->hasSSSE3())
8623     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8624             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8625       return Rotate;
8626
8627   // If we have direct support for blends, we should lower by decomposing into
8628   // a permute. That will be faster than the domain cross.
8629   if (IsBlendSupported)
8630     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8631                                                       Mask, DAG);
8632
8633   // Try to lower by permuting the inputs into an unpack instruction.
8634   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8635                                                             V2, Mask, DAG))
8636     return Unpack;
8637
8638   // We implement this with SHUFPS because it can blend from two vectors.
8639   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8640   // up the inputs, bypassing domain shift penalties that we would encur if we
8641   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8642   // relevant.
8643   return DAG.getBitcast(
8644       MVT::v4i32,
8645       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8646                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8647 }
8648
8649 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8650 /// shuffle lowering, and the most complex part.
8651 ///
8652 /// The lowering strategy is to try to form pairs of input lanes which are
8653 /// targeted at the same half of the final vector, and then use a dword shuffle
8654 /// to place them onto the right half, and finally unpack the paired lanes into
8655 /// their final position.
8656 ///
8657 /// The exact breakdown of how to form these dword pairs and align them on the
8658 /// correct sides is really tricky. See the comments within the function for
8659 /// more of the details.
8660 ///
8661 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8662 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8663 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8664 /// vector, form the analogous 128-bit 8-element Mask.
8665 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8666     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8667     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8668   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8669   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8670
8671   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8672   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8673   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8674
8675   SmallVector<int, 4> LoInputs;
8676   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8677                [](int M) { return M >= 0; });
8678   std::sort(LoInputs.begin(), LoInputs.end());
8679   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8680   SmallVector<int, 4> HiInputs;
8681   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8682                [](int M) { return M >= 0; });
8683   std::sort(HiInputs.begin(), HiInputs.end());
8684   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8685   int NumLToL =
8686       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8687   int NumHToL = LoInputs.size() - NumLToL;
8688   int NumLToH =
8689       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8690   int NumHToH = HiInputs.size() - NumLToH;
8691   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8692   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8693   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8694   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8695
8696   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8697   // such inputs we can swap two of the dwords across the half mark and end up
8698   // with <=2 inputs to each half in each half. Once there, we can fall through
8699   // to the generic code below. For example:
8700   //
8701   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8702   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8703   //
8704   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8705   // and an existing 2-into-2 on the other half. In this case we may have to
8706   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8707   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8708   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8709   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8710   // half than the one we target for fixing) will be fixed when we re-enter this
8711   // path. We will also combine away any sequence of PSHUFD instructions that
8712   // result into a single instruction. Here is an example of the tricky case:
8713   //
8714   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8715   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8716   //
8717   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8718   //
8719   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8720   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8721   //
8722   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8723   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8724   //
8725   // The result is fine to be handled by the generic logic.
8726   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8727                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8728                           int AOffset, int BOffset) {
8729     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8730            "Must call this with A having 3 or 1 inputs from the A half.");
8731     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8732            "Must call this with B having 1 or 3 inputs from the B half.");
8733     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8734            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8735
8736     bool ThreeAInputs = AToAInputs.size() == 3;
8737
8738     // Compute the index of dword with only one word among the three inputs in
8739     // a half by taking the sum of the half with three inputs and subtracting
8740     // the sum of the actual three inputs. The difference is the remaining
8741     // slot.
8742     int ADWord, BDWord;
8743     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8744     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8745     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8746     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8747     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8748     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8749     int TripleNonInputIdx =
8750         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8751     TripleDWord = TripleNonInputIdx / 2;
8752
8753     // We use xor with one to compute the adjacent DWord to whichever one the
8754     // OneInput is in.
8755     OneInputDWord = (OneInput / 2) ^ 1;
8756
8757     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8758     // and BToA inputs. If there is also such a problem with the BToB and AToB
8759     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8760     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8761     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8762     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8763       // Compute how many inputs will be flipped by swapping these DWords. We
8764       // need
8765       // to balance this to ensure we don't form a 3-1 shuffle in the other
8766       // half.
8767       int NumFlippedAToBInputs =
8768           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8769           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8770       int NumFlippedBToBInputs =
8771           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8772           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8773       if ((NumFlippedAToBInputs == 1 &&
8774            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8775           (NumFlippedBToBInputs == 1 &&
8776            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8777         // We choose whether to fix the A half or B half based on whether that
8778         // half has zero flipped inputs. At zero, we may not be able to fix it
8779         // with that half. We also bias towards fixing the B half because that
8780         // will more commonly be the high half, and we have to bias one way.
8781         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8782                                                        ArrayRef<int> Inputs) {
8783           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8784           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8785                                          PinnedIdx ^ 1) != Inputs.end();
8786           // Determine whether the free index is in the flipped dword or the
8787           // unflipped dword based on where the pinned index is. We use this bit
8788           // in an xor to conditionally select the adjacent dword.
8789           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8790           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8791                                              FixFreeIdx) != Inputs.end();
8792           if (IsFixIdxInput == IsFixFreeIdxInput)
8793             FixFreeIdx += 1;
8794           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8795                                         FixFreeIdx) != Inputs.end();
8796           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8797                  "We need to be changing the number of flipped inputs!");
8798           int PSHUFHalfMask[] = {0, 1, 2, 3};
8799           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8800           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8801                           MVT::v8i16, V,
8802                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8803
8804           for (int &M : Mask)
8805             if (M != -1 && M == FixIdx)
8806               M = FixFreeIdx;
8807             else if (M != -1 && M == FixFreeIdx)
8808               M = FixIdx;
8809         };
8810         if (NumFlippedBToBInputs != 0) {
8811           int BPinnedIdx =
8812               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8813           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8814         } else {
8815           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8816           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8817           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8818         }
8819       }
8820     }
8821
8822     int PSHUFDMask[] = {0, 1, 2, 3};
8823     PSHUFDMask[ADWord] = BDWord;
8824     PSHUFDMask[BDWord] = ADWord;
8825     V = DAG.getBitcast(
8826         VT,
8827         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8828                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8829
8830     // Adjust the mask to match the new locations of A and B.
8831     for (int &M : Mask)
8832       if (M != -1 && M/2 == ADWord)
8833         M = 2 * BDWord + M % 2;
8834       else if (M != -1 && M/2 == BDWord)
8835         M = 2 * ADWord + M % 2;
8836
8837     // Recurse back into this routine to re-compute state now that this isn't
8838     // a 3 and 1 problem.
8839     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8840                                                      DAG);
8841   };
8842   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8843     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8844   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8845     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8846
8847   // At this point there are at most two inputs to the low and high halves from
8848   // each half. That means the inputs can always be grouped into dwords and
8849   // those dwords can then be moved to the correct half with a dword shuffle.
8850   // We use at most one low and one high word shuffle to collect these paired
8851   // inputs into dwords, and finally a dword shuffle to place them.
8852   int PSHUFLMask[4] = {-1, -1, -1, -1};
8853   int PSHUFHMask[4] = {-1, -1, -1, -1};
8854   int PSHUFDMask[4] = {-1, -1, -1, -1};
8855
8856   // First fix the masks for all the inputs that are staying in their
8857   // original halves. This will then dictate the targets of the cross-half
8858   // shuffles.
8859   auto fixInPlaceInputs =
8860       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8861                     MutableArrayRef<int> SourceHalfMask,
8862                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8863     if (InPlaceInputs.empty())
8864       return;
8865     if (InPlaceInputs.size() == 1) {
8866       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8867           InPlaceInputs[0] - HalfOffset;
8868       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8869       return;
8870     }
8871     if (IncomingInputs.empty()) {
8872       // Just fix all of the in place inputs.
8873       for (int Input : InPlaceInputs) {
8874         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8875         PSHUFDMask[Input / 2] = Input / 2;
8876       }
8877       return;
8878     }
8879
8880     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8881     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8882         InPlaceInputs[0] - HalfOffset;
8883     // Put the second input next to the first so that they are packed into
8884     // a dword. We find the adjacent index by toggling the low bit.
8885     int AdjIndex = InPlaceInputs[0] ^ 1;
8886     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8887     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8888     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8889   };
8890   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8891   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8892
8893   // Now gather the cross-half inputs and place them into a free dword of
8894   // their target half.
8895   // FIXME: This operation could almost certainly be simplified dramatically to
8896   // look more like the 3-1 fixing operation.
8897   auto moveInputsToRightHalf = [&PSHUFDMask](
8898       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8899       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8900       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8901       int DestOffset) {
8902     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8903       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8904     };
8905     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8906                                                int Word) {
8907       int LowWord = Word & ~1;
8908       int HighWord = Word | 1;
8909       return isWordClobbered(SourceHalfMask, LowWord) ||
8910              isWordClobbered(SourceHalfMask, HighWord);
8911     };
8912
8913     if (IncomingInputs.empty())
8914       return;
8915
8916     if (ExistingInputs.empty()) {
8917       // Map any dwords with inputs from them into the right half.
8918       for (int Input : IncomingInputs) {
8919         // If the source half mask maps over the inputs, turn those into
8920         // swaps and use the swapped lane.
8921         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8922           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8923             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8924                 Input - SourceOffset;
8925             // We have to swap the uses in our half mask in one sweep.
8926             for (int &M : HalfMask)
8927               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8928                 M = Input;
8929               else if (M == Input)
8930                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8931           } else {
8932             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8933                        Input - SourceOffset &&
8934                    "Previous placement doesn't match!");
8935           }
8936           // Note that this correctly re-maps both when we do a swap and when
8937           // we observe the other side of the swap above. We rely on that to
8938           // avoid swapping the members of the input list directly.
8939           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8940         }
8941
8942         // Map the input's dword into the correct half.
8943         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8944           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8945         else
8946           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8947                      Input / 2 &&
8948                  "Previous placement doesn't match!");
8949       }
8950
8951       // And just directly shift any other-half mask elements to be same-half
8952       // as we will have mirrored the dword containing the element into the
8953       // same position within that half.
8954       for (int &M : HalfMask)
8955         if (M >= SourceOffset && M < SourceOffset + 4) {
8956           M = M - SourceOffset + DestOffset;
8957           assert(M >= 0 && "This should never wrap below zero!");
8958         }
8959       return;
8960     }
8961
8962     // Ensure we have the input in a viable dword of its current half. This
8963     // is particularly tricky because the original position may be clobbered
8964     // by inputs being moved and *staying* in that half.
8965     if (IncomingInputs.size() == 1) {
8966       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8967         int InputFixed = std::find(std::begin(SourceHalfMask),
8968                                    std::end(SourceHalfMask), -1) -
8969                          std::begin(SourceHalfMask) + SourceOffset;
8970         SourceHalfMask[InputFixed - SourceOffset] =
8971             IncomingInputs[0] - SourceOffset;
8972         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8973                      InputFixed);
8974         IncomingInputs[0] = InputFixed;
8975       }
8976     } else if (IncomingInputs.size() == 2) {
8977       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8978           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8979         // We have two non-adjacent or clobbered inputs we need to extract from
8980         // the source half. To do this, we need to map them into some adjacent
8981         // dword slot in the source mask.
8982         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8983                               IncomingInputs[1] - SourceOffset};
8984
8985         // If there is a free slot in the source half mask adjacent to one of
8986         // the inputs, place the other input in it. We use (Index XOR 1) to
8987         // compute an adjacent index.
8988         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8989             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8990           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8991           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8992           InputsFixed[1] = InputsFixed[0] ^ 1;
8993         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8994                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8995           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8996           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8997           InputsFixed[0] = InputsFixed[1] ^ 1;
8998         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8999                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9000           // The two inputs are in the same DWord but it is clobbered and the
9001           // adjacent DWord isn't used at all. Move both inputs to the free
9002           // slot.
9003           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9004           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9005           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9006           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9007         } else {
9008           // The only way we hit this point is if there is no clobbering
9009           // (because there are no off-half inputs to this half) and there is no
9010           // free slot adjacent to one of the inputs. In this case, we have to
9011           // swap an input with a non-input.
9012           for (int i = 0; i < 4; ++i)
9013             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9014                    "We can't handle any clobbers here!");
9015           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9016                  "Cannot have adjacent inputs here!");
9017
9018           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9019           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9020
9021           // We also have to update the final source mask in this case because
9022           // it may need to undo the above swap.
9023           for (int &M : FinalSourceHalfMask)
9024             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9025               M = InputsFixed[1] + SourceOffset;
9026             else if (M == InputsFixed[1] + SourceOffset)
9027               M = (InputsFixed[0] ^ 1) + SourceOffset;
9028
9029           InputsFixed[1] = InputsFixed[0] ^ 1;
9030         }
9031
9032         // Point everything at the fixed inputs.
9033         for (int &M : HalfMask)
9034           if (M == IncomingInputs[0])
9035             M = InputsFixed[0] + SourceOffset;
9036           else if (M == IncomingInputs[1])
9037             M = InputsFixed[1] + SourceOffset;
9038
9039         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9040         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9041       }
9042     } else {
9043       llvm_unreachable("Unhandled input size!");
9044     }
9045
9046     // Now hoist the DWord down to the right half.
9047     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9048     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9049     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9050     for (int &M : HalfMask)
9051       for (int Input : IncomingInputs)
9052         if (M == Input)
9053           M = FreeDWord * 2 + Input % 2;
9054   };
9055   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9056                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9057   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9058                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9059
9060   // Now enact all the shuffles we've computed to move the inputs into their
9061   // target half.
9062   if (!isNoopShuffleMask(PSHUFLMask))
9063     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9064                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9065   if (!isNoopShuffleMask(PSHUFHMask))
9066     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9067                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9068   if (!isNoopShuffleMask(PSHUFDMask))
9069     V = DAG.getBitcast(
9070         VT,
9071         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9072                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9073
9074   // At this point, each half should contain all its inputs, and we can then
9075   // just shuffle them into their final position.
9076   assert(std::count_if(LoMask.begin(), LoMask.end(),
9077                        [](int M) { return M >= 4; }) == 0 &&
9078          "Failed to lift all the high half inputs to the low mask!");
9079   assert(std::count_if(HiMask.begin(), HiMask.end(),
9080                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9081          "Failed to lift all the low half inputs to the high mask!");
9082
9083   // Do a half shuffle for the low mask.
9084   if (!isNoopShuffleMask(LoMask))
9085     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9086                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9087
9088   // Do a half shuffle with the high mask after shifting its values down.
9089   for (int &M : HiMask)
9090     if (M >= 0)
9091       M -= 4;
9092   if (!isNoopShuffleMask(HiMask))
9093     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9094                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9095
9096   return V;
9097 }
9098
9099 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9100 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9101                                           SDValue V2, ArrayRef<int> Mask,
9102                                           SelectionDAG &DAG, bool &V1InUse,
9103                                           bool &V2InUse) {
9104   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9105   SDValue V1Mask[16];
9106   SDValue V2Mask[16];
9107   V1InUse = false;
9108   V2InUse = false;
9109
9110   int Size = Mask.size();
9111   int Scale = 16 / Size;
9112   for (int i = 0; i < 16; ++i) {
9113     if (Mask[i / Scale] == -1) {
9114       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9115     } else {
9116       const int ZeroMask = 0x80;
9117       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9118                                           : ZeroMask;
9119       int V2Idx = Mask[i / Scale] < Size
9120                       ? ZeroMask
9121                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9122       if (Zeroable[i / Scale])
9123         V1Idx = V2Idx = ZeroMask;
9124       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9125       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9126       V1InUse |= (ZeroMask != V1Idx);
9127       V2InUse |= (ZeroMask != V2Idx);
9128     }
9129   }
9130
9131   if (V1InUse)
9132     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9133                      DAG.getBitcast(MVT::v16i8, V1),
9134                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9135   if (V2InUse)
9136     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9137                      DAG.getBitcast(MVT::v16i8, V2),
9138                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9139
9140   // If we need shuffled inputs from both, blend the two.
9141   SDValue V;
9142   if (V1InUse && V2InUse)
9143     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9144   else
9145     V = V1InUse ? V1 : V2;
9146
9147   // Cast the result back to the correct type.
9148   return DAG.getBitcast(VT, V);
9149 }
9150
9151 /// \brief Generic lowering of 8-lane i16 shuffles.
9152 ///
9153 /// This handles both single-input shuffles and combined shuffle/blends with
9154 /// two inputs. The single input shuffles are immediately delegated to
9155 /// a dedicated lowering routine.
9156 ///
9157 /// The blends are lowered in one of three fundamental ways. If there are few
9158 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9159 /// of the input is significantly cheaper when lowered as an interleaving of
9160 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9161 /// halves of the inputs separately (making them have relatively few inputs)
9162 /// and then concatenate them.
9163 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9164                                        const X86Subtarget *Subtarget,
9165                                        SelectionDAG &DAG) {
9166   SDLoc DL(Op);
9167   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9168   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9169   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9170   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9171   ArrayRef<int> OrigMask = SVOp->getMask();
9172   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9173                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9174   MutableArrayRef<int> Mask(MaskStorage);
9175
9176   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9177
9178   // Whenever we can lower this as a zext, that instruction is strictly faster
9179   // than any alternative.
9180   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9181           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9182     return ZExt;
9183
9184   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9185   (void)isV1;
9186   auto isV2 = [](int M) { return M >= 8; };
9187
9188   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9189
9190   if (NumV2Inputs == 0) {
9191     // Check for being able to broadcast a single element.
9192     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9193                                                           Mask, Subtarget, DAG))
9194       return Broadcast;
9195
9196     // Try to use shift instructions.
9197     if (SDValue Shift =
9198             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9199       return Shift;
9200
9201     // Use dedicated unpack instructions for masks that match their pattern.
9202     if (SDValue V =
9203             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9204       return V;
9205
9206     // Try to use byte rotation instructions.
9207     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9208                                                         Mask, Subtarget, DAG))
9209       return Rotate;
9210
9211     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9212                                                      Subtarget, DAG);
9213   }
9214
9215   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9216          "All single-input shuffles should be canonicalized to be V1-input "
9217          "shuffles.");
9218
9219   // Try to use shift instructions.
9220   if (SDValue Shift =
9221           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9222     return Shift;
9223
9224   // See if we can use SSE4A Extraction / Insertion.
9225   if (Subtarget->hasSSE4A())
9226     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9227       return V;
9228
9229   // There are special ways we can lower some single-element blends.
9230   if (NumV2Inputs == 1)
9231     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9232                                                          Mask, Subtarget, DAG))
9233       return V;
9234
9235   // We have different paths for blend lowering, but they all must use the
9236   // *exact* same predicate.
9237   bool IsBlendSupported = Subtarget->hasSSE41();
9238   if (IsBlendSupported)
9239     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9240                                                   Subtarget, DAG))
9241       return Blend;
9242
9243   if (SDValue Masked =
9244           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9245     return Masked;
9246
9247   // Use dedicated unpack instructions for masks that match their pattern.
9248   if (SDValue V =
9249           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9250     return V;
9251
9252   // Try to use byte rotation instructions.
9253   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9254           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9255     return Rotate;
9256
9257   if (SDValue BitBlend =
9258           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9259     return BitBlend;
9260
9261   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9262                                                             V2, Mask, DAG))
9263     return Unpack;
9264
9265   // If we can't directly blend but can use PSHUFB, that will be better as it
9266   // can both shuffle and set up the inefficient blend.
9267   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9268     bool V1InUse, V2InUse;
9269     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9270                                       V1InUse, V2InUse);
9271   }
9272
9273   // We can always bit-blend if we have to so the fallback strategy is to
9274   // decompose into single-input permutes and blends.
9275   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9276                                                       Mask, DAG);
9277 }
9278
9279 /// \brief Check whether a compaction lowering can be done by dropping even
9280 /// elements and compute how many times even elements must be dropped.
9281 ///
9282 /// This handles shuffles which take every Nth element where N is a power of
9283 /// two. Example shuffle masks:
9284 ///
9285 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9286 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9287 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9288 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9289 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9290 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9291 ///
9292 /// Any of these lanes can of course be undef.
9293 ///
9294 /// This routine only supports N <= 3.
9295 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9296 /// for larger N.
9297 ///
9298 /// \returns N above, or the number of times even elements must be dropped if
9299 /// there is such a number. Otherwise returns zero.
9300 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9301   // Figure out whether we're looping over two inputs or just one.
9302   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9303
9304   // The modulus for the shuffle vector entries is based on whether this is
9305   // a single input or not.
9306   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9307   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9308          "We should only be called with masks with a power-of-2 size!");
9309
9310   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9311
9312   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9313   // and 2^3 simultaneously. This is because we may have ambiguity with
9314   // partially undef inputs.
9315   bool ViableForN[3] = {true, true, true};
9316
9317   for (int i = 0, e = Mask.size(); i < e; ++i) {
9318     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9319     // want.
9320     if (Mask[i] == -1)
9321       continue;
9322
9323     bool IsAnyViable = false;
9324     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9325       if (ViableForN[j]) {
9326         uint64_t N = j + 1;
9327
9328         // The shuffle mask must be equal to (i * 2^N) % M.
9329         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9330           IsAnyViable = true;
9331         else
9332           ViableForN[j] = false;
9333       }
9334     // Early exit if we exhaust the possible powers of two.
9335     if (!IsAnyViable)
9336       break;
9337   }
9338
9339   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9340     if (ViableForN[j])
9341       return j + 1;
9342
9343   // Return 0 as there is no viable power of two.
9344   return 0;
9345 }
9346
9347 /// \brief Generic lowering of v16i8 shuffles.
9348 ///
9349 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9350 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9351 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9352 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9353 /// back together.
9354 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9355                                        const X86Subtarget *Subtarget,
9356                                        SelectionDAG &DAG) {
9357   SDLoc DL(Op);
9358   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9359   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9360   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9361   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9362   ArrayRef<int> Mask = SVOp->getMask();
9363   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9364
9365   // Try to use shift instructions.
9366   if (SDValue Shift =
9367           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9368     return Shift;
9369
9370   // Try to use byte rotation instructions.
9371   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9372           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9373     return Rotate;
9374
9375   // Try to use a zext lowering.
9376   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9377           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9378     return ZExt;
9379
9380   // See if we can use SSE4A Extraction / Insertion.
9381   if (Subtarget->hasSSE4A())
9382     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9383       return V;
9384
9385   int NumV2Elements =
9386       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9387
9388   // For single-input shuffles, there are some nicer lowering tricks we can use.
9389   if (NumV2Elements == 0) {
9390     // Check for being able to broadcast a single element.
9391     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9392                                                           Mask, Subtarget, DAG))
9393       return Broadcast;
9394
9395     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9396     // Notably, this handles splat and partial-splat shuffles more efficiently.
9397     // However, it only makes sense if the pre-duplication shuffle simplifies
9398     // things significantly. Currently, this means we need to be able to
9399     // express the pre-duplication shuffle as an i16 shuffle.
9400     //
9401     // FIXME: We should check for other patterns which can be widened into an
9402     // i16 shuffle as well.
9403     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9404       for (int i = 0; i < 16; i += 2)
9405         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9406           return false;
9407
9408       return true;
9409     };
9410     auto tryToWidenViaDuplication = [&]() -> SDValue {
9411       if (!canWidenViaDuplication(Mask))
9412         return SDValue();
9413       SmallVector<int, 4> LoInputs;
9414       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9415                    [](int M) { return M >= 0 && M < 8; });
9416       std::sort(LoInputs.begin(), LoInputs.end());
9417       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9418                      LoInputs.end());
9419       SmallVector<int, 4> HiInputs;
9420       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9421                    [](int M) { return M >= 8; });
9422       std::sort(HiInputs.begin(), HiInputs.end());
9423       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9424                      HiInputs.end());
9425
9426       bool TargetLo = LoInputs.size() >= HiInputs.size();
9427       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9428       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9429
9430       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9431       SmallDenseMap<int, int, 8> LaneMap;
9432       for (int I : InPlaceInputs) {
9433         PreDupI16Shuffle[I/2] = I/2;
9434         LaneMap[I] = I;
9435       }
9436       int j = TargetLo ? 0 : 4, je = j + 4;
9437       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9438         // Check if j is already a shuffle of this input. This happens when
9439         // there are two adjacent bytes after we move the low one.
9440         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9441           // If we haven't yet mapped the input, search for a slot into which
9442           // we can map it.
9443           while (j < je && PreDupI16Shuffle[j] != -1)
9444             ++j;
9445
9446           if (j == je)
9447             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9448             return SDValue();
9449
9450           // Map this input with the i16 shuffle.
9451           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9452         }
9453
9454         // Update the lane map based on the mapping we ended up with.
9455         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9456       }
9457       V1 = DAG.getBitcast(
9458           MVT::v16i8,
9459           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9460                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9461
9462       // Unpack the bytes to form the i16s that will be shuffled into place.
9463       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9464                        MVT::v16i8, V1, V1);
9465
9466       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9467       for (int i = 0; i < 16; ++i)
9468         if (Mask[i] != -1) {
9469           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9470           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9471           if (PostDupI16Shuffle[i / 2] == -1)
9472             PostDupI16Shuffle[i / 2] = MappedMask;
9473           else
9474             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9475                    "Conflicting entrties in the original shuffle!");
9476         }
9477       return DAG.getBitcast(
9478           MVT::v16i8,
9479           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9480                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9481     };
9482     if (SDValue V = tryToWidenViaDuplication())
9483       return V;
9484   }
9485
9486   if (SDValue Masked =
9487           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9488     return Masked;
9489
9490   // Use dedicated unpack instructions for masks that match their pattern.
9491   if (SDValue V =
9492           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9493     return V;
9494
9495   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9496   // with PSHUFB. It is important to do this before we attempt to generate any
9497   // blends but after all of the single-input lowerings. If the single input
9498   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9499   // want to preserve that and we can DAG combine any longer sequences into
9500   // a PSHUFB in the end. But once we start blending from multiple inputs,
9501   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9502   // and there are *very* few patterns that would actually be faster than the
9503   // PSHUFB approach because of its ability to zero lanes.
9504   //
9505   // FIXME: The only exceptions to the above are blends which are exact
9506   // interleavings with direct instructions supporting them. We currently don't
9507   // handle those well here.
9508   if (Subtarget->hasSSSE3()) {
9509     bool V1InUse = false;
9510     bool V2InUse = false;
9511
9512     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9513                                                 DAG, V1InUse, V2InUse);
9514
9515     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9516     // do so. This avoids using them to handle blends-with-zero which is
9517     // important as a single pshufb is significantly faster for that.
9518     if (V1InUse && V2InUse) {
9519       if (Subtarget->hasSSE41())
9520         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9521                                                       Mask, Subtarget, DAG))
9522           return Blend;
9523
9524       // We can use an unpack to do the blending rather than an or in some
9525       // cases. Even though the or may be (very minorly) more efficient, we
9526       // preference this lowering because there are common cases where part of
9527       // the complexity of the shuffles goes away when we do the final blend as
9528       // an unpack.
9529       // FIXME: It might be worth trying to detect if the unpack-feeding
9530       // shuffles will both be pshufb, in which case we shouldn't bother with
9531       // this.
9532       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9533               DL, MVT::v16i8, V1, V2, Mask, DAG))
9534         return Unpack;
9535     }
9536
9537     return PSHUFB;
9538   }
9539
9540   // There are special ways we can lower some single-element blends.
9541   if (NumV2Elements == 1)
9542     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9543                                                          Mask, Subtarget, DAG))
9544       return V;
9545
9546   if (SDValue BitBlend =
9547           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9548     return BitBlend;
9549
9550   // Check whether a compaction lowering can be done. This handles shuffles
9551   // which take every Nth element for some even N. See the helper function for
9552   // details.
9553   //
9554   // We special case these as they can be particularly efficiently handled with
9555   // the PACKUSB instruction on x86 and they show up in common patterns of
9556   // rearranging bytes to truncate wide elements.
9557   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9558     // NumEvenDrops is the power of two stride of the elements. Another way of
9559     // thinking about it is that we need to drop the even elements this many
9560     // times to get the original input.
9561     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9562
9563     // First we need to zero all the dropped bytes.
9564     assert(NumEvenDrops <= 3 &&
9565            "No support for dropping even elements more than 3 times.");
9566     // We use the mask type to pick which bytes are preserved based on how many
9567     // elements are dropped.
9568     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9569     SDValue ByteClearMask = DAG.getBitcast(
9570         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9571     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9572     if (!IsSingleInput)
9573       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9574
9575     // Now pack things back together.
9576     V1 = DAG.getBitcast(MVT::v8i16, V1);
9577     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9578     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9579     for (int i = 1; i < NumEvenDrops; ++i) {
9580       Result = DAG.getBitcast(MVT::v8i16, Result);
9581       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9582     }
9583
9584     return Result;
9585   }
9586
9587   // Handle multi-input cases by blending single-input shuffles.
9588   if (NumV2Elements > 0)
9589     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9590                                                       Mask, DAG);
9591
9592   // The fallback path for single-input shuffles widens this into two v8i16
9593   // vectors with unpacks, shuffles those, and then pulls them back together
9594   // with a pack.
9595   SDValue V = V1;
9596
9597   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9598   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9599   for (int i = 0; i < 16; ++i)
9600     if (Mask[i] >= 0)
9601       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9602
9603   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9604
9605   SDValue VLoHalf, VHiHalf;
9606   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9607   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9608   // i16s.
9609   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9610                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9611       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9612                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9613     // Use a mask to drop the high bytes.
9614     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9615     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9616                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9617
9618     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9619     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9620
9621     // Squash the masks to point directly into VLoHalf.
9622     for (int &M : LoBlendMask)
9623       if (M >= 0)
9624         M /= 2;
9625     for (int &M : HiBlendMask)
9626       if (M >= 0)
9627         M /= 2;
9628   } else {
9629     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9630     // VHiHalf so that we can blend them as i16s.
9631     VLoHalf = DAG.getBitcast(
9632         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9633     VHiHalf = DAG.getBitcast(
9634         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9635   }
9636
9637   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9638   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9639
9640   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9641 }
9642
9643 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9644 ///
9645 /// This routine breaks down the specific type of 128-bit shuffle and
9646 /// dispatches to the lowering routines accordingly.
9647 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9648                                         MVT VT, const X86Subtarget *Subtarget,
9649                                         SelectionDAG &DAG) {
9650   switch (VT.SimpleTy) {
9651   case MVT::v2i64:
9652     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9653   case MVT::v2f64:
9654     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9655   case MVT::v4i32:
9656     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9657   case MVT::v4f32:
9658     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9659   case MVT::v8i16:
9660     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9661   case MVT::v16i8:
9662     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9663
9664   default:
9665     llvm_unreachable("Unimplemented!");
9666   }
9667 }
9668
9669 /// \brief Helper function to test whether a shuffle mask could be
9670 /// simplified by widening the elements being shuffled.
9671 ///
9672 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9673 /// leaves it in an unspecified state.
9674 ///
9675 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9676 /// shuffle masks. The latter have the special property of a '-2' representing
9677 /// a zero-ed lane of a vector.
9678 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9679                                     SmallVectorImpl<int> &WidenedMask) {
9680   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9681     // If both elements are undef, its trivial.
9682     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9683       WidenedMask.push_back(SM_SentinelUndef);
9684       continue;
9685     }
9686
9687     // Check for an undef mask and a mask value properly aligned to fit with
9688     // a pair of values. If we find such a case, use the non-undef mask's value.
9689     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9690       WidenedMask.push_back(Mask[i + 1] / 2);
9691       continue;
9692     }
9693     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9694       WidenedMask.push_back(Mask[i] / 2);
9695       continue;
9696     }
9697
9698     // When zeroing, we need to spread the zeroing across both lanes to widen.
9699     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9700       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9701           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9702         WidenedMask.push_back(SM_SentinelZero);
9703         continue;
9704       }
9705       return false;
9706     }
9707
9708     // Finally check if the two mask values are adjacent and aligned with
9709     // a pair.
9710     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9711       WidenedMask.push_back(Mask[i] / 2);
9712       continue;
9713     }
9714
9715     // Otherwise we can't safely widen the elements used in this shuffle.
9716     return false;
9717   }
9718   assert(WidenedMask.size() == Mask.size() / 2 &&
9719          "Incorrect size of mask after widening the elements!");
9720
9721   return true;
9722 }
9723
9724 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9725 ///
9726 /// This routine just extracts two subvectors, shuffles them independently, and
9727 /// then concatenates them back together. This should work effectively with all
9728 /// AVX vector shuffle types.
9729 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9730                                           SDValue V2, ArrayRef<int> Mask,
9731                                           SelectionDAG &DAG) {
9732   assert(VT.getSizeInBits() >= 256 &&
9733          "Only for 256-bit or wider vector shuffles!");
9734   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9735   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9736
9737   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9738   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9739
9740   int NumElements = VT.getVectorNumElements();
9741   int SplitNumElements = NumElements / 2;
9742   MVT ScalarVT = VT.getScalarType();
9743   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9744
9745   // Rather than splitting build-vectors, just build two narrower build
9746   // vectors. This helps shuffling with splats and zeros.
9747   auto SplitVector = [&](SDValue V) {
9748     while (V.getOpcode() == ISD::BITCAST)
9749       V = V->getOperand(0);
9750
9751     MVT OrigVT = V.getSimpleValueType();
9752     int OrigNumElements = OrigVT.getVectorNumElements();
9753     int OrigSplitNumElements = OrigNumElements / 2;
9754     MVT OrigScalarVT = OrigVT.getScalarType();
9755     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9756
9757     SDValue LoV, HiV;
9758
9759     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9760     if (!BV) {
9761       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9762                         DAG.getIntPtrConstant(0, DL));
9763       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9764                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9765     } else {
9766
9767       SmallVector<SDValue, 16> LoOps, HiOps;
9768       for (int i = 0; i < OrigSplitNumElements; ++i) {
9769         LoOps.push_back(BV->getOperand(i));
9770         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9771       }
9772       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9773       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9774     }
9775     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9776                           DAG.getBitcast(SplitVT, HiV));
9777   };
9778
9779   SDValue LoV1, HiV1, LoV2, HiV2;
9780   std::tie(LoV1, HiV1) = SplitVector(V1);
9781   std::tie(LoV2, HiV2) = SplitVector(V2);
9782
9783   // Now create two 4-way blends of these half-width vectors.
9784   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9785     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9786     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9787     for (int i = 0; i < SplitNumElements; ++i) {
9788       int M = HalfMask[i];
9789       if (M >= NumElements) {
9790         if (M >= NumElements + SplitNumElements)
9791           UseHiV2 = true;
9792         else
9793           UseLoV2 = true;
9794         V2BlendMask.push_back(M - NumElements);
9795         V1BlendMask.push_back(-1);
9796         BlendMask.push_back(SplitNumElements + i);
9797       } else if (M >= 0) {
9798         if (M >= SplitNumElements)
9799           UseHiV1 = true;
9800         else
9801           UseLoV1 = true;
9802         V2BlendMask.push_back(-1);
9803         V1BlendMask.push_back(M);
9804         BlendMask.push_back(i);
9805       } else {
9806         V2BlendMask.push_back(-1);
9807         V1BlendMask.push_back(-1);
9808         BlendMask.push_back(-1);
9809       }
9810     }
9811
9812     // Because the lowering happens after all combining takes place, we need to
9813     // manually combine these blend masks as much as possible so that we create
9814     // a minimal number of high-level vector shuffle nodes.
9815
9816     // First try just blending the halves of V1 or V2.
9817     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9818       return DAG.getUNDEF(SplitVT);
9819     if (!UseLoV2 && !UseHiV2)
9820       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9821     if (!UseLoV1 && !UseHiV1)
9822       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9823
9824     SDValue V1Blend, V2Blend;
9825     if (UseLoV1 && UseHiV1) {
9826       V1Blend =
9827         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9828     } else {
9829       // We only use half of V1 so map the usage down into the final blend mask.
9830       V1Blend = UseLoV1 ? LoV1 : HiV1;
9831       for (int i = 0; i < SplitNumElements; ++i)
9832         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9833           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9834     }
9835     if (UseLoV2 && UseHiV2) {
9836       V2Blend =
9837         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9838     } else {
9839       // We only use half of V2 so map the usage down into the final blend mask.
9840       V2Blend = UseLoV2 ? LoV2 : HiV2;
9841       for (int i = 0; i < SplitNumElements; ++i)
9842         if (BlendMask[i] >= SplitNumElements)
9843           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9844     }
9845     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9846   };
9847   SDValue Lo = HalfBlend(LoMask);
9848   SDValue Hi = HalfBlend(HiMask);
9849   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9850 }
9851
9852 /// \brief Either split a vector in halves or decompose the shuffles and the
9853 /// blend.
9854 ///
9855 /// This is provided as a good fallback for many lowerings of non-single-input
9856 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9857 /// between splitting the shuffle into 128-bit components and stitching those
9858 /// back together vs. extracting the single-input shuffles and blending those
9859 /// results.
9860 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9861                                                 SDValue V2, ArrayRef<int> Mask,
9862                                                 SelectionDAG &DAG) {
9863   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9864                                             "lower single-input shuffles as it "
9865                                             "could then recurse on itself.");
9866   int Size = Mask.size();
9867
9868   // If this can be modeled as a broadcast of two elements followed by a blend,
9869   // prefer that lowering. This is especially important because broadcasts can
9870   // often fold with memory operands.
9871   auto DoBothBroadcast = [&] {
9872     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9873     for (int M : Mask)
9874       if (M >= Size) {
9875         if (V2BroadcastIdx == -1)
9876           V2BroadcastIdx = M - Size;
9877         else if (M - Size != V2BroadcastIdx)
9878           return false;
9879       } else if (M >= 0) {
9880         if (V1BroadcastIdx == -1)
9881           V1BroadcastIdx = M;
9882         else if (M != V1BroadcastIdx)
9883           return false;
9884       }
9885     return true;
9886   };
9887   if (DoBothBroadcast())
9888     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9889                                                       DAG);
9890
9891   // If the inputs all stem from a single 128-bit lane of each input, then we
9892   // split them rather than blending because the split will decompose to
9893   // unusually few instructions.
9894   int LaneCount = VT.getSizeInBits() / 128;
9895   int LaneSize = Size / LaneCount;
9896   SmallBitVector LaneInputs[2];
9897   LaneInputs[0].resize(LaneCount, false);
9898   LaneInputs[1].resize(LaneCount, false);
9899   for (int i = 0; i < Size; ++i)
9900     if (Mask[i] >= 0)
9901       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9902   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9903     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9904
9905   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9906   // that the decomposed single-input shuffles don't end up here.
9907   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9908 }
9909
9910 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9911 /// a permutation and blend of those lanes.
9912 ///
9913 /// This essentially blends the out-of-lane inputs to each lane into the lane
9914 /// from a permuted copy of the vector. This lowering strategy results in four
9915 /// instructions in the worst case for a single-input cross lane shuffle which
9916 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9917 /// of. Special cases for each particular shuffle pattern should be handled
9918 /// prior to trying this lowering.
9919 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9920                                                        SDValue V1, SDValue V2,
9921                                                        ArrayRef<int> Mask,
9922                                                        SelectionDAG &DAG) {
9923   // FIXME: This should probably be generalized for 512-bit vectors as well.
9924   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9925   int LaneSize = Mask.size() / 2;
9926
9927   // If there are only inputs from one 128-bit lane, splitting will in fact be
9928   // less expensive. The flags track whether the given lane contains an element
9929   // that crosses to another lane.
9930   bool LaneCrossing[2] = {false, false};
9931   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9932     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9933       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9934   if (!LaneCrossing[0] || !LaneCrossing[1])
9935     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9936
9937   if (isSingleInputShuffleMask(Mask)) {
9938     SmallVector<int, 32> FlippedBlendMask;
9939     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9940       FlippedBlendMask.push_back(
9941           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9942                                   ? Mask[i]
9943                                   : Mask[i] % LaneSize +
9944                                         (i / LaneSize) * LaneSize + Size));
9945
9946     // Flip the vector, and blend the results which should now be in-lane. The
9947     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9948     // 5 for the high source. The value 3 selects the high half of source 2 and
9949     // the value 2 selects the low half of source 2. We only use source 2 to
9950     // allow folding it into a memory operand.
9951     unsigned PERMMask = 3 | 2 << 4;
9952     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9953                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9954     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9955   }
9956
9957   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9958   // will be handled by the above logic and a blend of the results, much like
9959   // other patterns in AVX.
9960   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9961 }
9962
9963 /// \brief Handle lowering 2-lane 128-bit shuffles.
9964 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9965                                         SDValue V2, ArrayRef<int> Mask,
9966                                         const X86Subtarget *Subtarget,
9967                                         SelectionDAG &DAG) {
9968   // TODO: If minimizing size and one of the inputs is a zero vector and the
9969   // the zero vector has only one use, we could use a VPERM2X128 to save the
9970   // instruction bytes needed to explicitly generate the zero vector.
9971
9972   // Blends are faster and handle all the non-lane-crossing cases.
9973   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9974                                                 Subtarget, DAG))
9975     return Blend;
9976
9977   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9978   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9979
9980   // If either input operand is a zero vector, use VPERM2X128 because its mask
9981   // allows us to replace the zero input with an implicit zero.
9982   if (!IsV1Zero && !IsV2Zero) {
9983     // Check for patterns which can be matched with a single insert of a 128-bit
9984     // subvector.
9985     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9986     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9987       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9988                                    VT.getVectorNumElements() / 2);
9989       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9990                                 DAG.getIntPtrConstant(0, DL));
9991       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9992                                 OnlyUsesV1 ? V1 : V2,
9993                                 DAG.getIntPtrConstant(0, DL));
9994       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9995     }
9996   }
9997
9998   // Otherwise form a 128-bit permutation. After accounting for undefs,
9999   // convert the 64-bit shuffle mask selection values into 128-bit
10000   // selection bits by dividing the indexes by 2 and shifting into positions
10001   // defined by a vperm2*128 instruction's immediate control byte.
10002
10003   // The immediate permute control byte looks like this:
10004   //    [1:0] - select 128 bits from sources for low half of destination
10005   //    [2]   - ignore
10006   //    [3]   - zero low half of destination
10007   //    [5:4] - select 128 bits from sources for high half of destination
10008   //    [6]   - ignore
10009   //    [7]   - zero high half of destination
10010
10011   int MaskLO = Mask[0];
10012   if (MaskLO == SM_SentinelUndef)
10013     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10014
10015   int MaskHI = Mask[2];
10016   if (MaskHI == SM_SentinelUndef)
10017     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10018
10019   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10020
10021   // If either input is a zero vector, replace it with an undef input.
10022   // Shuffle mask values <  4 are selecting elements of V1.
10023   // Shuffle mask values >= 4 are selecting elements of V2.
10024   // Adjust each half of the permute mask by clearing the half that was
10025   // selecting the zero vector and setting the zero mask bit.
10026   if (IsV1Zero) {
10027     V1 = DAG.getUNDEF(VT);
10028     if (MaskLO < 4)
10029       PermMask = (PermMask & 0xf0) | 0x08;
10030     if (MaskHI < 4)
10031       PermMask = (PermMask & 0x0f) | 0x80;
10032   }
10033   if (IsV2Zero) {
10034     V2 = DAG.getUNDEF(VT);
10035     if (MaskLO >= 4)
10036       PermMask = (PermMask & 0xf0) | 0x08;
10037     if (MaskHI >= 4)
10038       PermMask = (PermMask & 0x0f) | 0x80;
10039   }
10040
10041   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10042                      DAG.getConstant(PermMask, DL, MVT::i8));
10043 }
10044
10045 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10046 /// shuffling each lane.
10047 ///
10048 /// This will only succeed when the result of fixing the 128-bit lanes results
10049 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10050 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10051 /// the lane crosses early and then use simpler shuffles within each lane.
10052 ///
10053 /// FIXME: It might be worthwhile at some point to support this without
10054 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10055 /// in x86 only floating point has interesting non-repeating shuffles, and even
10056 /// those are still *marginally* more expensive.
10057 static SDValue lowerVectorShuffleByMerging128BitLanes(
10058     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10059     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10060   assert(!isSingleInputShuffleMask(Mask) &&
10061          "This is only useful with multiple inputs.");
10062
10063   int Size = Mask.size();
10064   int LaneSize = 128 / VT.getScalarSizeInBits();
10065   int NumLanes = Size / LaneSize;
10066   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10067
10068   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10069   // check whether the in-128-bit lane shuffles share a repeating pattern.
10070   SmallVector<int, 4> Lanes;
10071   Lanes.resize(NumLanes, -1);
10072   SmallVector<int, 4> InLaneMask;
10073   InLaneMask.resize(LaneSize, -1);
10074   for (int i = 0; i < Size; ++i) {
10075     if (Mask[i] < 0)
10076       continue;
10077
10078     int j = i / LaneSize;
10079
10080     if (Lanes[j] < 0) {
10081       // First entry we've seen for this lane.
10082       Lanes[j] = Mask[i] / LaneSize;
10083     } else if (Lanes[j] != Mask[i] / LaneSize) {
10084       // This doesn't match the lane selected previously!
10085       return SDValue();
10086     }
10087
10088     // Check that within each lane we have a consistent shuffle mask.
10089     int k = i % LaneSize;
10090     if (InLaneMask[k] < 0) {
10091       InLaneMask[k] = Mask[i] % LaneSize;
10092     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10093       // This doesn't fit a repeating in-lane mask.
10094       return SDValue();
10095     }
10096   }
10097
10098   // First shuffle the lanes into place.
10099   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10100                                 VT.getSizeInBits() / 64);
10101   SmallVector<int, 8> LaneMask;
10102   LaneMask.resize(NumLanes * 2, -1);
10103   for (int i = 0; i < NumLanes; ++i)
10104     if (Lanes[i] >= 0) {
10105       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10106       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10107     }
10108
10109   V1 = DAG.getBitcast(LaneVT, V1);
10110   V2 = DAG.getBitcast(LaneVT, V2);
10111   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10112
10113   // Cast it back to the type we actually want.
10114   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10115
10116   // Now do a simple shuffle that isn't lane crossing.
10117   SmallVector<int, 8> NewMask;
10118   NewMask.resize(Size, -1);
10119   for (int i = 0; i < Size; ++i)
10120     if (Mask[i] >= 0)
10121       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10122   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10123          "Must not introduce lane crosses at this point!");
10124
10125   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10126 }
10127
10128 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10129 /// given mask.
10130 ///
10131 /// This returns true if the elements from a particular input are already in the
10132 /// slot required by the given mask and require no permutation.
10133 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10134   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10135   int Size = Mask.size();
10136   for (int i = 0; i < Size; ++i)
10137     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10138       return false;
10139
10140   return true;
10141 }
10142
10143 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10144                                             ArrayRef<int> Mask, SDValue V1,
10145                                             SDValue V2, SelectionDAG &DAG) {
10146
10147   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10148   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10149   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10150   int NumElts = VT.getVectorNumElements();
10151   bool ShufpdMask = true;
10152   bool CommutableMask = true;
10153   unsigned Immediate = 0;
10154   for (int i = 0; i < NumElts; ++i) {
10155     if (Mask[i] < 0)
10156       continue;
10157     int Val = (i & 6) + NumElts * (i & 1);
10158     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10159     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10160       ShufpdMask = false;
10161     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10162       CommutableMask = false;
10163     Immediate |= (Mask[i] % 2) << i;
10164   }
10165   if (ShufpdMask)
10166     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10167                        DAG.getConstant(Immediate, DL, MVT::i8));
10168   if (CommutableMask)
10169     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10170                        DAG.getConstant(Immediate, DL, MVT::i8));
10171   return SDValue();
10172 }
10173
10174 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10175 ///
10176 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10177 /// isn't available.
10178 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10179                                        const X86Subtarget *Subtarget,
10180                                        SelectionDAG &DAG) {
10181   SDLoc DL(Op);
10182   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10183   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10184   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10185   ArrayRef<int> Mask = SVOp->getMask();
10186   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10187
10188   SmallVector<int, 4> WidenedMask;
10189   if (canWidenShuffleElements(Mask, WidenedMask))
10190     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10191                                     DAG);
10192
10193   if (isSingleInputShuffleMask(Mask)) {
10194     // Check for being able to broadcast a single element.
10195     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10196                                                           Mask, Subtarget, DAG))
10197       return Broadcast;
10198
10199     // Use low duplicate instructions for masks that match their pattern.
10200     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10201       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10202
10203     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10204       // Non-half-crossing single input shuffles can be lowerid with an
10205       // interleaved permutation.
10206       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10207                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10208       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10209                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10210     }
10211
10212     // With AVX2 we have direct support for this permutation.
10213     if (Subtarget->hasAVX2())
10214       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10215                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10216
10217     // Otherwise, fall back.
10218     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10219                                                    DAG);
10220   }
10221
10222   // Use dedicated unpack instructions for masks that match their pattern.
10223   if (SDValue V =
10224           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10225     return V;
10226
10227   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10228                                                 Subtarget, DAG))
10229     return Blend;
10230
10231   // Check if the blend happens to exactly fit that of SHUFPD.
10232   if (SDValue Op =
10233       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10234     return Op;
10235
10236   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10237   // shuffle. However, if we have AVX2 and either inputs are already in place,
10238   // we will be able to shuffle even across lanes the other input in a single
10239   // instruction so skip this pattern.
10240   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10241                                  isShuffleMaskInputInPlace(1, Mask))))
10242     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10243             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10244       return Result;
10245
10246   // If we have AVX2 then we always want to lower with a blend because an v4 we
10247   // can fully permute the elements.
10248   if (Subtarget->hasAVX2())
10249     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10250                                                       Mask, DAG);
10251
10252   // Otherwise fall back on generic lowering.
10253   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10254 }
10255
10256 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10257 ///
10258 /// This routine is only called when we have AVX2 and thus a reasonable
10259 /// instruction set for v4i64 shuffling..
10260 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10261                                        const X86Subtarget *Subtarget,
10262                                        SelectionDAG &DAG) {
10263   SDLoc DL(Op);
10264   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10265   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10266   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10267   ArrayRef<int> Mask = SVOp->getMask();
10268   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10269   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10270
10271   SmallVector<int, 4> WidenedMask;
10272   if (canWidenShuffleElements(Mask, WidenedMask))
10273     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10274                                     DAG);
10275
10276   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10277                                                 Subtarget, DAG))
10278     return Blend;
10279
10280   // Check for being able to broadcast a single element.
10281   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10282                                                         Mask, Subtarget, DAG))
10283     return Broadcast;
10284
10285   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10286   // use lower latency instructions that will operate on both 128-bit lanes.
10287   SmallVector<int, 2> RepeatedMask;
10288   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10289     if (isSingleInputShuffleMask(Mask)) {
10290       int PSHUFDMask[] = {-1, -1, -1, -1};
10291       for (int i = 0; i < 2; ++i)
10292         if (RepeatedMask[i] >= 0) {
10293           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10294           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10295         }
10296       return DAG.getBitcast(
10297           MVT::v4i64,
10298           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10299                       DAG.getBitcast(MVT::v8i32, V1),
10300                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10301     }
10302   }
10303
10304   // AVX2 provides a direct instruction for permuting a single input across
10305   // lanes.
10306   if (isSingleInputShuffleMask(Mask))
10307     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10308                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10309
10310   // Try to use shift instructions.
10311   if (SDValue Shift =
10312           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10313     return Shift;
10314
10315   // Use dedicated unpack instructions for masks that match their pattern.
10316   if (SDValue V =
10317           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10318     return V;
10319
10320   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10321   // shuffle. However, if we have AVX2 and either inputs are already in place,
10322   // we will be able to shuffle even across lanes the other input in a single
10323   // instruction so skip this pattern.
10324   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10325                                  isShuffleMaskInputInPlace(1, Mask))))
10326     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10327             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10328       return Result;
10329
10330   // Otherwise fall back on generic blend lowering.
10331   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10332                                                     Mask, DAG);
10333 }
10334
10335 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10336 ///
10337 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10338 /// isn't available.
10339 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10340                                        const X86Subtarget *Subtarget,
10341                                        SelectionDAG &DAG) {
10342   SDLoc DL(Op);
10343   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10344   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10345   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10346   ArrayRef<int> Mask = SVOp->getMask();
10347   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10348
10349   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10350                                                 Subtarget, DAG))
10351     return Blend;
10352
10353   // Check for being able to broadcast a single element.
10354   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10355                                                         Mask, Subtarget, DAG))
10356     return Broadcast;
10357
10358   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10359   // options to efficiently lower the shuffle.
10360   SmallVector<int, 4> RepeatedMask;
10361   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10362     assert(RepeatedMask.size() == 4 &&
10363            "Repeated masks must be half the mask width!");
10364
10365     // Use even/odd duplicate instructions for masks that match their pattern.
10366     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10367       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10368     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10369       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10370
10371     if (isSingleInputShuffleMask(Mask))
10372       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10373                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10374
10375     // Use dedicated unpack instructions for masks that match their pattern.
10376     if (SDValue V =
10377             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10378       return V;
10379
10380     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10381     // have already handled any direct blends. We also need to squash the
10382     // repeated mask into a simulated v4f32 mask.
10383     for (int i = 0; i < 4; ++i)
10384       if (RepeatedMask[i] >= 8)
10385         RepeatedMask[i] -= 4;
10386     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10387   }
10388
10389   // If we have a single input shuffle with different shuffle patterns in the
10390   // two 128-bit lanes use the variable mask to VPERMILPS.
10391   if (isSingleInputShuffleMask(Mask)) {
10392     SDValue VPermMask[8];
10393     for (int i = 0; i < 8; ++i)
10394       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10395                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10396     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10397       return DAG.getNode(
10398           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10399           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10400
10401     if (Subtarget->hasAVX2())
10402       return DAG.getNode(
10403           X86ISD::VPERMV, DL, MVT::v8f32,
10404           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10405                                                  MVT::v8i32, VPermMask)),
10406           V1);
10407
10408     // Otherwise, fall back.
10409     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10410                                                    DAG);
10411   }
10412
10413   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10414   // shuffle.
10415   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10416           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10417     return Result;
10418
10419   // If we have AVX2 then we always want to lower with a blend because at v8 we
10420   // can fully permute the elements.
10421   if (Subtarget->hasAVX2())
10422     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10423                                                       Mask, DAG);
10424
10425   // Otherwise fall back on generic lowering.
10426   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10427 }
10428
10429 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10430 ///
10431 /// This routine is only called when we have AVX2 and thus a reasonable
10432 /// instruction set for v8i32 shuffling..
10433 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10434                                        const X86Subtarget *Subtarget,
10435                                        SelectionDAG &DAG) {
10436   SDLoc DL(Op);
10437   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10438   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10439   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10440   ArrayRef<int> Mask = SVOp->getMask();
10441   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10442   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10443
10444   // Whenever we can lower this as a zext, that instruction is strictly faster
10445   // than any alternative. It also allows us to fold memory operands into the
10446   // shuffle in many cases.
10447   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10448                                                          Mask, Subtarget, DAG))
10449     return ZExt;
10450
10451   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10452                                                 Subtarget, DAG))
10453     return Blend;
10454
10455   // Check for being able to broadcast a single element.
10456   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10457                                                         Mask, Subtarget, DAG))
10458     return Broadcast;
10459
10460   // If the shuffle mask is repeated in each 128-bit lane we can use more
10461   // efficient instructions that mirror the shuffles across the two 128-bit
10462   // lanes.
10463   SmallVector<int, 4> RepeatedMask;
10464   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10465     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10466     if (isSingleInputShuffleMask(Mask))
10467       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10468                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10469
10470     // Use dedicated unpack instructions for masks that match their pattern.
10471     if (SDValue V =
10472             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10473       return V;
10474   }
10475
10476   // Try to use shift instructions.
10477   if (SDValue Shift =
10478           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10479     return Shift;
10480
10481   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10482           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10483     return Rotate;
10484
10485   // If the shuffle patterns aren't repeated but it is a single input, directly
10486   // generate a cross-lane VPERMD instruction.
10487   if (isSingleInputShuffleMask(Mask)) {
10488     SDValue VPermMask[8];
10489     for (int i = 0; i < 8; ++i)
10490       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10491                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10492     return DAG.getNode(
10493         X86ISD::VPERMV, DL, MVT::v8i32,
10494         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10495   }
10496
10497   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10498   // shuffle.
10499   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10500           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10501     return Result;
10502
10503   // Otherwise fall back on generic blend lowering.
10504   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10505                                                     Mask, DAG);
10506 }
10507
10508 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10509 ///
10510 /// This routine is only called when we have AVX2 and thus a reasonable
10511 /// instruction set for v16i16 shuffling..
10512 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10513                                         const X86Subtarget *Subtarget,
10514                                         SelectionDAG &DAG) {
10515   SDLoc DL(Op);
10516   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10517   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10518   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10519   ArrayRef<int> Mask = SVOp->getMask();
10520   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10521   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10522
10523   // Whenever we can lower this as a zext, that instruction is strictly faster
10524   // than any alternative. It also allows us to fold memory operands into the
10525   // shuffle in many cases.
10526   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10527                                                          Mask, Subtarget, DAG))
10528     return ZExt;
10529
10530   // Check for being able to broadcast a single element.
10531   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10532                                                         Mask, Subtarget, DAG))
10533     return Broadcast;
10534
10535   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10536                                                 Subtarget, DAG))
10537     return Blend;
10538
10539   // Use dedicated unpack instructions for masks that match their pattern.
10540   if (SDValue V =
10541           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10542     return V;
10543
10544   // Try to use shift instructions.
10545   if (SDValue Shift =
10546           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10547     return Shift;
10548
10549   // Try to use byte rotation instructions.
10550   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10551           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10552     return Rotate;
10553
10554   if (isSingleInputShuffleMask(Mask)) {
10555     // There are no generalized cross-lane shuffle operations available on i16
10556     // element types.
10557     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10558       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10559                                                      Mask, DAG);
10560
10561     SmallVector<int, 8> RepeatedMask;
10562     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10563       // As this is a single-input shuffle, the repeated mask should be
10564       // a strictly valid v8i16 mask that we can pass through to the v8i16
10565       // lowering to handle even the v16 case.
10566       return lowerV8I16GeneralSingleInputVectorShuffle(
10567           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10568     }
10569
10570     SDValue PSHUFBMask[32];
10571     for (int i = 0; i < 16; ++i) {
10572       if (Mask[i] == -1) {
10573         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10574         continue;
10575       }
10576
10577       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10578       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10579       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10580       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10581     }
10582     return DAG.getBitcast(MVT::v16i16,
10583                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10584                                       DAG.getBitcast(MVT::v32i8, V1),
10585                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10586                                                   MVT::v32i8, PSHUFBMask)));
10587   }
10588
10589   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10590   // shuffle.
10591   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10592           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10593     return Result;
10594
10595   // Otherwise fall back on generic lowering.
10596   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10597 }
10598
10599 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10600 ///
10601 /// This routine is only called when we have AVX2 and thus a reasonable
10602 /// instruction set for v32i8 shuffling..
10603 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10604                                        const X86Subtarget *Subtarget,
10605                                        SelectionDAG &DAG) {
10606   SDLoc DL(Op);
10607   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10608   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10609   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10610   ArrayRef<int> Mask = SVOp->getMask();
10611   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10612   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10613
10614   // Whenever we can lower this as a zext, that instruction is strictly faster
10615   // than any alternative. It also allows us to fold memory operands into the
10616   // shuffle in many cases.
10617   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10618                                                          Mask, Subtarget, DAG))
10619     return ZExt;
10620
10621   // Check for being able to broadcast a single element.
10622   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10623                                                         Mask, Subtarget, DAG))
10624     return Broadcast;
10625
10626   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10627                                                 Subtarget, DAG))
10628     return Blend;
10629
10630   // Use dedicated unpack instructions for masks that match their pattern.
10631   if (SDValue V =
10632           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10633     return V;
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 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10738 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10739                                              ArrayRef<int> Mask,
10740                                              SDValue V1, SDValue V2,
10741                                              SelectionDAG &DAG) {
10742   assert(VT.getScalarSizeInBits() == 64 &&
10743          "Unexpected element type size for 128bit shuffle.");
10744
10745   // To handle 256 bit vector requires VLX and most probably
10746   // function lowerV2X128VectorShuffle() is better solution.
10747   assert(VT.getSizeInBits() == 512 &&
10748          "Unexpected vector size for 128bit shuffle.");
10749
10750   SmallVector<int, 4> WidenedMask;
10751   if (!canWidenShuffleElements(Mask, WidenedMask))
10752     return SDValue();
10753
10754   // Form a 128-bit permutation.
10755   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10756   // bits defined by a vshuf64x2 instruction's immediate control byte.
10757   unsigned PermMask = 0, Imm = 0;
10758   unsigned ControlBitsNum = WidenedMask.size() / 2;
10759
10760   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10761     if (WidenedMask[i] == SM_SentinelZero)
10762       return SDValue();
10763
10764     // Use first element in place of undef mask.
10765     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10766     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10767   }
10768
10769   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10770                      DAG.getConstant(PermMask, DL, MVT::i8));
10771 }
10772
10773 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10774                                            ArrayRef<int> Mask, SDValue V1,
10775                                            SDValue V2, SelectionDAG &DAG) {
10776
10777   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10778
10779   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10780   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10781
10782   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10783   if (isSingleInputShuffleMask(Mask))
10784     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10785
10786   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10787 }
10788
10789 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10790 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10791                                        const X86Subtarget *Subtarget,
10792                                        SelectionDAG &DAG) {
10793   SDLoc DL(Op);
10794   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10795   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10797   ArrayRef<int> Mask = SVOp->getMask();
10798   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10799
10800   if (SDValue Shuf128 =
10801           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10802     return Shuf128;
10803
10804   if (SDValue Unpck =
10805           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10806     return Unpck;
10807
10808   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10809 }
10810
10811 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10812 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10813                                        const X86Subtarget *Subtarget,
10814                                        SelectionDAG &DAG) {
10815   SDLoc DL(Op);
10816   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10817   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10818   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10819   ArrayRef<int> Mask = SVOp->getMask();
10820   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10821
10822   if (SDValue Unpck =
10823           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10824     return Unpck;
10825
10826   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10827 }
10828
10829 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10830 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10831                                        const X86Subtarget *Subtarget,
10832                                        SelectionDAG &DAG) {
10833   SDLoc DL(Op);
10834   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10835   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10836   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10837   ArrayRef<int> Mask = SVOp->getMask();
10838   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10839
10840   if (SDValue Shuf128 =
10841           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10842     return Shuf128;
10843
10844   if (SDValue Unpck =
10845           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10846     return Unpck;
10847
10848   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10849 }
10850
10851 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10852 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10853                                        const X86Subtarget *Subtarget,
10854                                        SelectionDAG &DAG) {
10855   SDLoc DL(Op);
10856   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10857   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10858   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10859   ArrayRef<int> Mask = SVOp->getMask();
10860   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10861
10862   if (SDValue Unpck =
10863           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10864     return Unpck;
10865
10866   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10867 }
10868
10869 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10870 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10871                                         const X86Subtarget *Subtarget,
10872                                         SelectionDAG &DAG) {
10873   SDLoc DL(Op);
10874   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10875   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10876   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10877   ArrayRef<int> Mask = SVOp->getMask();
10878   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10879   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10880
10881   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10882 }
10883
10884 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10885 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10886                                        const X86Subtarget *Subtarget,
10887                                        SelectionDAG &DAG) {
10888   SDLoc DL(Op);
10889   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10890   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10891   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10892   ArrayRef<int> Mask = SVOp->getMask();
10893   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10894   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10895
10896   // FIXME: Implement direct support for this type!
10897   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10898 }
10899
10900 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10901 ///
10902 /// This routine either breaks down the specific type of a 512-bit x86 vector
10903 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10904 /// together based on the available instructions.
10905 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10906                                         MVT VT, const X86Subtarget *Subtarget,
10907                                         SelectionDAG &DAG) {
10908   SDLoc DL(Op);
10909   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10910   ArrayRef<int> Mask = SVOp->getMask();
10911   assert(Subtarget->hasAVX512() &&
10912          "Cannot lower 512-bit vectors w/ basic ISA!");
10913
10914   // Check for being able to broadcast a single element.
10915   if (SDValue Broadcast =
10916           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10917     return Broadcast;
10918
10919   // Dispatch to each element type for lowering. If we don't have supprot for
10920   // specific element type shuffles at 512 bits, immediately split them and
10921   // lower them. Each lowering routine of a given type is allowed to assume that
10922   // the requisite ISA extensions for that element type are available.
10923   switch (VT.SimpleTy) {
10924   case MVT::v8f64:
10925     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10926   case MVT::v16f32:
10927     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10928   case MVT::v8i64:
10929     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10930   case MVT::v16i32:
10931     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10932   case MVT::v32i16:
10933     if (Subtarget->hasBWI())
10934       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10935     break;
10936   case MVT::v64i8:
10937     if (Subtarget->hasBWI())
10938       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10939     break;
10940
10941   default:
10942     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10943   }
10944
10945   // Otherwise fall back on splitting.
10946   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10947 }
10948
10949 // Lower vXi1 vector shuffles.
10950 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10951 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10952 // vector, shuffle and then truncate it back.
10953 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10954                                       MVT VT, const X86Subtarget *Subtarget,
10955                                       SelectionDAG &DAG) {
10956   SDLoc DL(Op);
10957   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10958   ArrayRef<int> Mask = SVOp->getMask();
10959   assert(Subtarget->hasAVX512() &&
10960          "Cannot lower 512-bit vectors w/o basic ISA!");
10961   EVT ExtVT;
10962   switch (VT.SimpleTy) {
10963   default:
10964     llvm_unreachable("Expected a vector of i1 elements");
10965   case MVT::v2i1:
10966     ExtVT = MVT::v2i64;
10967     break;
10968   case MVT::v4i1:
10969     ExtVT = MVT::v4i32;
10970     break;
10971   case MVT::v8i1:
10972     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10973     break;
10974   case MVT::v16i1:
10975     ExtVT = MVT::v16i32;
10976     break;
10977   case MVT::v32i1:
10978     ExtVT = MVT::v32i16;
10979     break;
10980   case MVT::v64i1:
10981     ExtVT = MVT::v64i8;
10982     break;
10983   }
10984
10985   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10986     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10987   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10988     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10989   else
10990     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10991
10992   if (V2.isUndef())
10993     V2 = DAG.getUNDEF(ExtVT);
10994   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10995     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10996   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10997     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10998   else
10999     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11000   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11001                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11002 }
11003 /// \brief Top-level lowering for x86 vector shuffles.
11004 ///
11005 /// This handles decomposition, canonicalization, and lowering of all x86
11006 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11007 /// above in helper routines. The canonicalization attempts to widen shuffles
11008 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11009 /// s.t. only one of the two inputs needs to be tested, etc.
11010 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11011                                   SelectionDAG &DAG) {
11012   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11013   ArrayRef<int> Mask = SVOp->getMask();
11014   SDValue V1 = Op.getOperand(0);
11015   SDValue V2 = Op.getOperand(1);
11016   MVT VT = Op.getSimpleValueType();
11017   int NumElements = VT.getVectorNumElements();
11018   SDLoc dl(Op);
11019   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
11020
11021   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11022          "Can't lower MMX shuffles");
11023
11024   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11025   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11026   if (V1IsUndef && V2IsUndef)
11027     return DAG.getUNDEF(VT);
11028
11029   // When we create a shuffle node we put the UNDEF node to second operand,
11030   // but in some cases the first operand may be transformed to UNDEF.
11031   // In this case we should just commute the node.
11032   if (V1IsUndef)
11033     return DAG.getCommutedVectorShuffle(*SVOp);
11034
11035   // Check for non-undef masks pointing at an undef vector and make the masks
11036   // undef as well. This makes it easier to match the shuffle based solely on
11037   // the mask.
11038   if (V2IsUndef)
11039     for (int M : Mask)
11040       if (M >= NumElements) {
11041         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11042         for (int &M : NewMask)
11043           if (M >= NumElements)
11044             M = -1;
11045         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11046       }
11047
11048   // We actually see shuffles that are entirely re-arrangements of a set of
11049   // zero inputs. This mostly happens while decomposing complex shuffles into
11050   // simple ones. Directly lower these as a buildvector of zeros.
11051   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11052   if (Zeroable.all())
11053     return getZeroVector(VT, Subtarget, DAG, dl);
11054
11055   // Try to collapse shuffles into using a vector type with fewer elements but
11056   // wider element types. We cap this to not form integers or floating point
11057   // elements wider than 64 bits, but it might be interesting to form i128
11058   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11059   SmallVector<int, 16> WidenedMask;
11060   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11061       canWidenShuffleElements(Mask, WidenedMask)) {
11062     MVT NewEltVT = VT.isFloatingPoint()
11063                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11064                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11065     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11066     // Make sure that the new vector type is legal. For example, v2f64 isn't
11067     // legal on SSE1.
11068     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11069       V1 = DAG.getBitcast(NewVT, V1);
11070       V2 = DAG.getBitcast(NewVT, V2);
11071       return DAG.getBitcast(
11072           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11073     }
11074   }
11075
11076   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11077   for (int M : SVOp->getMask())
11078     if (M < 0)
11079       ++NumUndefElements;
11080     else if (M < NumElements)
11081       ++NumV1Elements;
11082     else
11083       ++NumV2Elements;
11084
11085   // Commute the shuffle as needed such that more elements come from V1 than
11086   // V2. This allows us to match the shuffle pattern strictly on how many
11087   // elements come from V1 without handling the symmetric cases.
11088   if (NumV2Elements > NumV1Elements)
11089     return DAG.getCommutedVectorShuffle(*SVOp);
11090
11091   // When the number of V1 and V2 elements are the same, try to minimize the
11092   // number of uses of V2 in the low half of the vector. When that is tied,
11093   // ensure that the sum of indices for V1 is equal to or lower than the sum
11094   // indices for V2. When those are equal, try to ensure that the number of odd
11095   // indices for V1 is lower than the number of odd indices for V2.
11096   if (NumV1Elements == NumV2Elements) {
11097     int LowV1Elements = 0, LowV2Elements = 0;
11098     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11099       if (M >= NumElements)
11100         ++LowV2Elements;
11101       else if (M >= 0)
11102         ++LowV1Elements;
11103     if (LowV2Elements > LowV1Elements) {
11104       return DAG.getCommutedVectorShuffle(*SVOp);
11105     } else if (LowV2Elements == LowV1Elements) {
11106       int SumV1Indices = 0, SumV2Indices = 0;
11107       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11108         if (SVOp->getMask()[i] >= NumElements)
11109           SumV2Indices += i;
11110         else if (SVOp->getMask()[i] >= 0)
11111           SumV1Indices += i;
11112       if (SumV2Indices < SumV1Indices) {
11113         return DAG.getCommutedVectorShuffle(*SVOp);
11114       } else if (SumV2Indices == SumV1Indices) {
11115         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11116         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11117           if (SVOp->getMask()[i] >= NumElements)
11118             NumV2OddIndices += i % 2;
11119           else if (SVOp->getMask()[i] >= 0)
11120             NumV1OddIndices += i % 2;
11121         if (NumV2OddIndices < NumV1OddIndices)
11122           return DAG.getCommutedVectorShuffle(*SVOp);
11123       }
11124     }
11125   }
11126
11127   // For each vector width, delegate to a specialized lowering routine.
11128   if (VT.getSizeInBits() == 128)
11129     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11130
11131   if (VT.getSizeInBits() == 256)
11132     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11133
11134   if (VT.getSizeInBits() == 512)
11135     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11136
11137   if (Is1BitVector)
11138     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11139   llvm_unreachable("Unimplemented!");
11140 }
11141
11142 // This function assumes its argument is a BUILD_VECTOR of constants or
11143 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11144 // true.
11145 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11146                                     unsigned &MaskValue) {
11147   MaskValue = 0;
11148   unsigned NumElems = BuildVector->getNumOperands();
11149   
11150   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11151   // We don't handle the >2 lanes case right now.
11152   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11153   if (NumLanes > 2)
11154     return false;
11155
11156   unsigned NumElemsInLane = NumElems / NumLanes;
11157
11158   // Blend for v16i16 should be symmetric for the both lanes.
11159   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11160     SDValue EltCond = BuildVector->getOperand(i);
11161     SDValue SndLaneEltCond =
11162         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11163
11164     int Lane1Cond = -1, Lane2Cond = -1;
11165     if (isa<ConstantSDNode>(EltCond))
11166       Lane1Cond = !isZero(EltCond);
11167     if (isa<ConstantSDNode>(SndLaneEltCond))
11168       Lane2Cond = !isZero(SndLaneEltCond);
11169
11170     unsigned LaneMask = 0;
11171     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11172       // Lane1Cond != 0, means we want the first argument.
11173       // Lane1Cond == 0, means we want the second argument.
11174       // The encoding of this argument is 0 for the first argument, 1
11175       // for the second. Therefore, invert the condition.
11176       LaneMask = !Lane1Cond << i;
11177     else if (Lane1Cond < 0)
11178       LaneMask = !Lane2Cond << i;
11179     else
11180       return false;
11181
11182     MaskValue |= LaneMask;
11183     if (NumLanes == 2)
11184       MaskValue |= LaneMask << NumElemsInLane;
11185   }
11186   return true;
11187 }
11188
11189 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11190 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11191                                            const X86Subtarget *Subtarget,
11192                                            SelectionDAG &DAG) {
11193   SDValue Cond = Op.getOperand(0);
11194   SDValue LHS = Op.getOperand(1);
11195   SDValue RHS = Op.getOperand(2);
11196   SDLoc dl(Op);
11197   MVT VT = Op.getSimpleValueType();
11198
11199   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11200     return SDValue();
11201   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11202
11203   // Only non-legal VSELECTs reach this lowering, convert those into generic
11204   // shuffles and re-use the shuffle lowering path for blends.
11205   SmallVector<int, 32> Mask;
11206   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11207     SDValue CondElt = CondBV->getOperand(i);
11208     Mask.push_back(
11209         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11210   }
11211   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11212 }
11213
11214 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11215   // A vselect where all conditions and data are constants can be optimized into
11216   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11217   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11218       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11219       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11220     return SDValue();
11221
11222   // Try to lower this to a blend-style vector shuffle. This can handle all
11223   // constant condition cases.
11224   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11225     return BlendOp;
11226
11227   // Variable blends are only legal from SSE4.1 onward.
11228   if (!Subtarget->hasSSE41())
11229     return SDValue();
11230
11231   // Only some types will be legal on some subtargets. If we can emit a legal
11232   // VSELECT-matching blend, return Op, and but if we need to expand, return
11233   // a null value.
11234   switch (Op.getSimpleValueType().SimpleTy) {
11235   default:
11236     // Most of the vector types have blends past SSE4.1.
11237     return Op;
11238
11239   case MVT::v32i8:
11240     // The byte blends for AVX vectors were introduced only in AVX2.
11241     if (Subtarget->hasAVX2())
11242       return Op;
11243
11244     return SDValue();
11245
11246   case MVT::v8i16:
11247   case MVT::v16i16:
11248     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11249     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11250       return Op;
11251
11252     // FIXME: We should custom lower this by fixing the condition and using i8
11253     // blends.
11254     return SDValue();
11255   }
11256 }
11257
11258 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11259   MVT VT = Op.getSimpleValueType();
11260   SDLoc dl(Op);
11261
11262   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11263     return SDValue();
11264
11265   if (VT.getSizeInBits() == 8) {
11266     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11267                                   Op.getOperand(0), Op.getOperand(1));
11268     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11269                                   DAG.getValueType(VT));
11270     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11271   }
11272
11273   if (VT.getSizeInBits() == 16) {
11274     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11275     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11276     if (Idx == 0)
11277       return DAG.getNode(
11278           ISD::TRUNCATE, dl, MVT::i16,
11279           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11280                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11281                       Op.getOperand(1)));
11282     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11283                                   Op.getOperand(0), Op.getOperand(1));
11284     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11285                                   DAG.getValueType(VT));
11286     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11287   }
11288
11289   if (VT == MVT::f32) {
11290     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11291     // the result back to FR32 register. It's only worth matching if the
11292     // result has a single use which is a store or a bitcast to i32.  And in
11293     // the case of a store, it's not worth it if the index is a constant 0,
11294     // because a MOVSSmr can be used instead, which is smaller and faster.
11295     if (!Op.hasOneUse())
11296       return SDValue();
11297     SDNode *User = *Op.getNode()->use_begin();
11298     if ((User->getOpcode() != ISD::STORE ||
11299          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11300           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11301         (User->getOpcode() != ISD::BITCAST ||
11302          User->getValueType(0) != MVT::i32))
11303       return SDValue();
11304     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11305                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11306                                   Op.getOperand(1));
11307     return DAG.getBitcast(MVT::f32, Extract);
11308   }
11309
11310   if (VT == MVT::i32 || VT == MVT::i64) {
11311     // ExtractPS/pextrq works with constant index.
11312     if (isa<ConstantSDNode>(Op.getOperand(1)))
11313       return Op;
11314   }
11315   return SDValue();
11316 }
11317
11318 /// Extract one bit from mask vector, like v16i1 or v8i1.
11319 /// AVX-512 feature.
11320 SDValue
11321 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11322   SDValue Vec = Op.getOperand(0);
11323   SDLoc dl(Vec);
11324   MVT VecVT = Vec.getSimpleValueType();
11325   SDValue Idx = Op.getOperand(1);
11326   MVT EltVT = Op.getSimpleValueType();
11327
11328   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11329   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11330          "Unexpected vector type in ExtractBitFromMaskVector");
11331
11332   // variable index can't be handled in mask registers,
11333   // extend vector to VR512
11334   if (!isa<ConstantSDNode>(Idx)) {
11335     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11336     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11337     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11338                               ExtVT.getVectorElementType(), Ext, Idx);
11339     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11340   }
11341
11342   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11343   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11344   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11345     rc = getRegClassFor(MVT::v16i1);
11346   unsigned MaxSift = rc->getSize()*8 - 1;
11347   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11348                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11349   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11350                     DAG.getConstant(MaxSift, dl, MVT::i8));
11351   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11352                        DAG.getIntPtrConstant(0, dl));
11353 }
11354
11355 SDValue
11356 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11357                                            SelectionDAG &DAG) const {
11358   SDLoc dl(Op);
11359   SDValue Vec = Op.getOperand(0);
11360   MVT VecVT = Vec.getSimpleValueType();
11361   SDValue Idx = Op.getOperand(1);
11362
11363   if (Op.getSimpleValueType() == MVT::i1)
11364     return ExtractBitFromMaskVector(Op, DAG);
11365
11366   if (!isa<ConstantSDNode>(Idx)) {
11367     if (VecVT.is512BitVector() ||
11368         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11369          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11370
11371       MVT MaskEltVT =
11372         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11373       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11374                                     MaskEltVT.getSizeInBits());
11375
11376       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11377       auto PtrVT = getPointerTy(DAG.getDataLayout());
11378       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11379                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11380                                  DAG.getConstant(0, dl, PtrVT));
11381       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11382       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11383                          DAG.getConstant(0, dl, PtrVT));
11384     }
11385     return SDValue();
11386   }
11387
11388   // If this is a 256-bit vector result, first extract the 128-bit vector and
11389   // then extract the element from the 128-bit vector.
11390   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11391
11392     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11393     // Get the 128-bit vector.
11394     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11395     MVT EltVT = VecVT.getVectorElementType();
11396
11397     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11398
11399     //if (IdxVal >= NumElems/2)
11400     //  IdxVal -= NumElems/2;
11401     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11402     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11403                        DAG.getConstant(IdxVal, dl, MVT::i32));
11404   }
11405
11406   assert(VecVT.is128BitVector() && "Unexpected vector length");
11407
11408   if (Subtarget->hasSSE41())
11409     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11410       return Res;
11411
11412   MVT VT = Op.getSimpleValueType();
11413   // TODO: handle v16i8.
11414   if (VT.getSizeInBits() == 16) {
11415     SDValue Vec = Op.getOperand(0);
11416     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11417     if (Idx == 0)
11418       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11419                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11420                                      DAG.getBitcast(MVT::v4i32, Vec),
11421                                      Op.getOperand(1)));
11422     // Transform it so it match pextrw which produces a 32-bit result.
11423     MVT EltVT = MVT::i32;
11424     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11425                                   Op.getOperand(0), Op.getOperand(1));
11426     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11427                                   DAG.getValueType(VT));
11428     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11429   }
11430
11431   if (VT.getSizeInBits() == 32) {
11432     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11433     if (Idx == 0)
11434       return Op;
11435
11436     // SHUFPS the element to the lowest double word, then movss.
11437     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11438     MVT VVT = Op.getOperand(0).getSimpleValueType();
11439     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11440                                        DAG.getUNDEF(VVT), Mask);
11441     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11442                        DAG.getIntPtrConstant(0, dl));
11443   }
11444
11445   if (VT.getSizeInBits() == 64) {
11446     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11447     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11448     //        to match extract_elt for f64.
11449     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11450     if (Idx == 0)
11451       return Op;
11452
11453     // UNPCKHPD the element to the lowest double word, then movsd.
11454     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11455     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11456     int Mask[2] = { 1, -1 };
11457     MVT VVT = Op.getOperand(0).getSimpleValueType();
11458     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11459                                        DAG.getUNDEF(VVT), Mask);
11460     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11461                        DAG.getIntPtrConstant(0, dl));
11462   }
11463
11464   return SDValue();
11465 }
11466
11467 /// Insert one bit to mask vector, like v16i1 or v8i1.
11468 /// AVX-512 feature.
11469 SDValue
11470 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11471   SDLoc dl(Op);
11472   SDValue Vec = Op.getOperand(0);
11473   SDValue Elt = Op.getOperand(1);
11474   SDValue Idx = Op.getOperand(2);
11475   MVT VecVT = Vec.getSimpleValueType();
11476
11477   if (!isa<ConstantSDNode>(Idx)) {
11478     // Non constant index. Extend source and destination,
11479     // insert element and then truncate the result.
11480     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11481     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11482     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11483       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11484       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11485     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11486   }
11487
11488   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11489   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11490   if (IdxVal)
11491     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11492                            DAG.getConstant(IdxVal, dl, MVT::i8));
11493   if (Vec.getOpcode() == ISD::UNDEF)
11494     return EltInVec;
11495   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11496 }
11497
11498 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11499                                                   SelectionDAG &DAG) const {
11500   MVT VT = Op.getSimpleValueType();
11501   MVT EltVT = VT.getVectorElementType();
11502
11503   if (EltVT == MVT::i1)
11504     return InsertBitToMaskVector(Op, DAG);
11505
11506   SDLoc dl(Op);
11507   SDValue N0 = Op.getOperand(0);
11508   SDValue N1 = Op.getOperand(1);
11509   SDValue N2 = Op.getOperand(2);
11510   if (!isa<ConstantSDNode>(N2))
11511     return SDValue();
11512   auto *N2C = cast<ConstantSDNode>(N2);
11513   unsigned IdxVal = N2C->getZExtValue();
11514
11515   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11516   // into that, and then insert the subvector back into the result.
11517   if (VT.is256BitVector() || VT.is512BitVector()) {
11518     // With a 256-bit vector, we can insert into the zero element efficiently
11519     // using a blend if we have AVX or AVX2 and the right data type.
11520     if (VT.is256BitVector() && IdxVal == 0) {
11521       // TODO: It is worthwhile to cast integer to floating point and back
11522       // and incur a domain crossing penalty if that's what we'll end up
11523       // doing anyway after extracting to a 128-bit vector.
11524       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11525           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11526         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11527         N2 = DAG.getIntPtrConstant(1, dl);
11528         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11529       }
11530     }
11531
11532     // Get the desired 128-bit vector chunk.
11533     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11534
11535     // Insert the element into the desired chunk.
11536     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11537     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11538
11539     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11540                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11541
11542     // Insert the changed part back into the bigger vector
11543     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11544   }
11545   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11546
11547   if (Subtarget->hasSSE41()) {
11548     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11549       unsigned Opc;
11550       if (VT == MVT::v8i16) {
11551         Opc = X86ISD::PINSRW;
11552       } else {
11553         assert(VT == MVT::v16i8);
11554         Opc = X86ISD::PINSRB;
11555       }
11556
11557       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11558       // 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(Opc, dl, VT, N0, N1, N2);
11564     }
11565
11566     if (EltVT == MVT::f32) {
11567       // Bits [7:6] of the constant are the source select. This will always be
11568       //   zero here. The DAG Combiner may combine an extract_elt index into
11569       //   these bits. For example (insert (extract, 3), 2) could be matched by
11570       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11571       // Bits [5:4] of the constant are the destination select. This is the
11572       //   value of the incoming immediate.
11573       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11574       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11575
11576       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11577       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11578         // If this is an insertion of 32-bits into the low 32-bits of
11579         // a vector, we prefer to generate a blend with immediate rather
11580         // than an insertps. Blends are simpler operations in hardware and so
11581         // will always have equal or better performance than insertps.
11582         // But if optimizing for size and there's a load folding opportunity,
11583         // generate insertps because blendps does not have a 32-bit memory
11584         // operand form.
11585         N2 = DAG.getIntPtrConstant(1, dl);
11586         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11587         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11588       }
11589       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11590       // Create this as a scalar to vector..
11591       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11592       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11593     }
11594
11595     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11596       // PINSR* works with constant index.
11597       return Op;
11598     }
11599   }
11600
11601   if (EltVT == MVT::i8)
11602     return SDValue();
11603
11604   if (EltVT.getSizeInBits() == 16) {
11605     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11606     // as its second argument.
11607     if (N1.getValueType() != MVT::i32)
11608       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11609     if (N2.getValueType() != MVT::i32)
11610       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11611     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11612   }
11613   return SDValue();
11614 }
11615
11616 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11617   SDLoc dl(Op);
11618   MVT OpVT = Op.getSimpleValueType();
11619
11620   // If this is a 256-bit vector result, first insert into a 128-bit
11621   // vector and then insert into the 256-bit vector.
11622   if (!OpVT.is128BitVector()) {
11623     // Insert into a 128-bit vector.
11624     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11625     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11626                                  OpVT.getVectorNumElements() / SizeFactor);
11627
11628     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11629
11630     // Insert the 128-bit vector.
11631     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11632   }
11633
11634   if (OpVT == MVT::v1i64 &&
11635       Op.getOperand(0).getValueType() == MVT::i64)
11636     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11637
11638   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11639   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11640   return DAG.getBitcast(
11641       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11642 }
11643
11644 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11645 // a simple subregister reference or explicit instructions to grab
11646 // upper bits of a vector.
11647 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11648                                       SelectionDAG &DAG) {
11649   SDLoc dl(Op);
11650   SDValue In =  Op.getOperand(0);
11651   SDValue Idx = Op.getOperand(1);
11652   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11653   MVT ResVT   = Op.getSimpleValueType();
11654   MVT InVT    = In.getSimpleValueType();
11655
11656   if (Subtarget->hasFp256()) {
11657     if (ResVT.is128BitVector() &&
11658         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11659         isa<ConstantSDNode>(Idx)) {
11660       return Extract128BitVector(In, IdxVal, DAG, dl);
11661     }
11662     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11663         isa<ConstantSDNode>(Idx)) {
11664       return Extract256BitVector(In, IdxVal, DAG, dl);
11665     }
11666   }
11667   return SDValue();
11668 }
11669
11670 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11671 // simple superregister reference or explicit instructions to insert
11672 // the upper bits of a vector.
11673 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11674                                      SelectionDAG &DAG) {
11675   if (!Subtarget->hasAVX())
11676     return SDValue();
11677
11678   SDLoc dl(Op);
11679   SDValue Vec = Op.getOperand(0);
11680   SDValue SubVec = Op.getOperand(1);
11681   SDValue Idx = Op.getOperand(2);
11682
11683   if (!isa<ConstantSDNode>(Idx))
11684     return SDValue();
11685
11686   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11687   MVT OpVT = Op.getSimpleValueType();
11688   MVT SubVecVT = SubVec.getSimpleValueType();
11689
11690   // Fold two 16-byte subvector loads into one 32-byte load:
11691   // (insert_subvector (insert_subvector undef, (load addr), 0),
11692   //                   (load addr + 16), Elts/2)
11693   // --> load32 addr
11694   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11695       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11696       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11697     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11698     if (Idx2 && Idx2->getZExtValue() == 0) {
11699       SDValue SubVec2 = Vec.getOperand(1);
11700       // If needed, look through a bitcast to get to the load.
11701       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11702         SubVec2 = SubVec2.getOperand(0);
11703
11704       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11705         bool Fast;
11706         unsigned Alignment = FirstLd->getAlignment();
11707         unsigned AS = FirstLd->getAddressSpace();
11708         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11709         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11710                                     OpVT, AS, Alignment, &Fast) && Fast) {
11711           SDValue Ops[] = { SubVec2, SubVec };
11712           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11713             return Ld;
11714         }
11715       }
11716     }
11717   }
11718
11719   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11720       SubVecVT.is128BitVector())
11721     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11722
11723   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11724     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11725
11726   if (OpVT.getVectorElementType() == MVT::i1) {
11727     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11728       return Op;
11729     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11730     SDValue Undef = DAG.getUNDEF(OpVT);
11731     unsigned NumElems = OpVT.getVectorNumElements();
11732     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11733
11734     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11735       // Zero upper bits of the Vec
11736       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11737       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11738
11739       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11740                                  SubVec, ZeroIdx);
11741       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11742       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11743     }
11744     if (IdxVal == 0) {
11745       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11746                                  SubVec, ZeroIdx);
11747       // Zero upper bits of the Vec2
11748       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11749       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11750       // Zero lower bits of the Vec
11751       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11752       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11753       // Merge them together
11754       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11755     }
11756   }
11757   return SDValue();
11758 }
11759
11760 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11761 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11762 // one of the above mentioned nodes. It has to be wrapped because otherwise
11763 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11764 // be used to form addressing mode. These wrapped nodes will be selected
11765 // into MOV32ri.
11766 SDValue
11767 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11768   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11769
11770   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11771   // global base reg.
11772   unsigned char OpFlag = 0;
11773   unsigned WrapperKind = X86ISD::Wrapper;
11774   CodeModel::Model M = DAG.getTarget().getCodeModel();
11775
11776   if (Subtarget->isPICStyleRIPRel() &&
11777       (M == CodeModel::Small || M == CodeModel::Kernel))
11778     WrapperKind = X86ISD::WrapperRIP;
11779   else if (Subtarget->isPICStyleGOT())
11780     OpFlag = X86II::MO_GOTOFF;
11781   else if (Subtarget->isPICStyleStubPIC())
11782     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11783
11784   auto PtrVT = getPointerTy(DAG.getDataLayout());
11785   SDValue Result = DAG.getTargetConstantPool(
11786       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11787   SDLoc DL(CP);
11788   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11789   // With PIC, the address is actually $g + Offset.
11790   if (OpFlag) {
11791     Result =
11792         DAG.getNode(ISD::ADD, DL, PtrVT,
11793                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11794   }
11795
11796   return Result;
11797 }
11798
11799 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11800   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11801
11802   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11803   // global base reg.
11804   unsigned char OpFlag = 0;
11805   unsigned WrapperKind = X86ISD::Wrapper;
11806   CodeModel::Model M = DAG.getTarget().getCodeModel();
11807
11808   if (Subtarget->isPICStyleRIPRel() &&
11809       (M == CodeModel::Small || M == CodeModel::Kernel))
11810     WrapperKind = X86ISD::WrapperRIP;
11811   else if (Subtarget->isPICStyleGOT())
11812     OpFlag = X86II::MO_GOTOFF;
11813   else if (Subtarget->isPICStyleStubPIC())
11814     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11815
11816   auto PtrVT = getPointerTy(DAG.getDataLayout());
11817   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11818   SDLoc DL(JT);
11819   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11820
11821   // With PIC, the address is actually $g + Offset.
11822   if (OpFlag)
11823     Result =
11824         DAG.getNode(ISD::ADD, DL, PtrVT,
11825                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11826
11827   return Result;
11828 }
11829
11830 SDValue
11831 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11832   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11833
11834   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11835   // global base reg.
11836   unsigned char OpFlag = 0;
11837   unsigned WrapperKind = X86ISD::Wrapper;
11838   CodeModel::Model M = DAG.getTarget().getCodeModel();
11839
11840   if (Subtarget->isPICStyleRIPRel() &&
11841       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11842     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11843       OpFlag = X86II::MO_GOTPCREL;
11844     WrapperKind = X86ISD::WrapperRIP;
11845   } else if (Subtarget->isPICStyleGOT()) {
11846     OpFlag = X86II::MO_GOT;
11847   } else if (Subtarget->isPICStyleStubPIC()) {
11848     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11849   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11850     OpFlag = X86II::MO_DARWIN_NONLAZY;
11851   }
11852
11853   auto PtrVT = getPointerTy(DAG.getDataLayout());
11854   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11855
11856   SDLoc DL(Op);
11857   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11858
11859   // With PIC, the address is actually $g + Offset.
11860   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11861       !Subtarget->is64Bit()) {
11862     Result =
11863         DAG.getNode(ISD::ADD, DL, PtrVT,
11864                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11865   }
11866
11867   // For symbols that require a load from a stub to get the address, emit the
11868   // load.
11869   if (isGlobalStubReference(OpFlag))
11870     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11871                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11872                          false, false, false, 0);
11873
11874   return Result;
11875 }
11876
11877 SDValue
11878 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11879   // Create the TargetBlockAddressAddress node.
11880   unsigned char OpFlags =
11881     Subtarget->ClassifyBlockAddressReference();
11882   CodeModel::Model M = DAG.getTarget().getCodeModel();
11883   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11884   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11885   SDLoc dl(Op);
11886   auto PtrVT = getPointerTy(DAG.getDataLayout());
11887   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11888
11889   if (Subtarget->isPICStyleRIPRel() &&
11890       (M == CodeModel::Small || M == CodeModel::Kernel))
11891     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11892   else
11893     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11894
11895   // With PIC, the address is actually $g + Offset.
11896   if (isGlobalRelativeToPICBase(OpFlags)) {
11897     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11898                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11899   }
11900
11901   return Result;
11902 }
11903
11904 SDValue
11905 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11906                                       int64_t Offset, SelectionDAG &DAG) const {
11907   // Create the TargetGlobalAddress node, folding in the constant
11908   // offset if it is legal.
11909   unsigned char OpFlags =
11910       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11911   CodeModel::Model M = DAG.getTarget().getCodeModel();
11912   auto PtrVT = getPointerTy(DAG.getDataLayout());
11913   SDValue Result;
11914   if (OpFlags == X86II::MO_NO_FLAG &&
11915       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11916     // A direct static reference to a global.
11917     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11918     Offset = 0;
11919   } else {
11920     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11921   }
11922
11923   if (Subtarget->isPICStyleRIPRel() &&
11924       (M == CodeModel::Small || M == CodeModel::Kernel))
11925     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11926   else
11927     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11928
11929   // With PIC, the address is actually $g + Offset.
11930   if (isGlobalRelativeToPICBase(OpFlags)) {
11931     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11932                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11933   }
11934
11935   // For globals that require a load from a stub to get the address, emit the
11936   // load.
11937   if (isGlobalStubReference(OpFlags))
11938     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11939                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11940                          false, false, false, 0);
11941
11942   // If there was a non-zero offset that we didn't fold, create an explicit
11943   // addition for it.
11944   if (Offset != 0)
11945     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11946                          DAG.getConstant(Offset, dl, PtrVT));
11947
11948   return Result;
11949 }
11950
11951 SDValue
11952 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11953   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11954   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11955   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11956 }
11957
11958 static SDValue
11959 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11960            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11961            unsigned char OperandFlags, bool LocalDynamic = false) {
11962   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11963   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11964   SDLoc dl(GA);
11965   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11966                                            GA->getValueType(0),
11967                                            GA->getOffset(),
11968                                            OperandFlags);
11969
11970   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11971                                            : X86ISD::TLSADDR;
11972
11973   if (InFlag) {
11974     SDValue Ops[] = { Chain,  TGA, *InFlag };
11975     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11976   } else {
11977     SDValue Ops[]  = { Chain, TGA };
11978     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11979   }
11980
11981   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11982   MFI->setAdjustsStack(true);
11983   MFI->setHasCalls(true);
11984
11985   SDValue Flag = Chain.getValue(1);
11986   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11987 }
11988
11989 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11990 static SDValue
11991 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11992                                 const EVT PtrVT) {
11993   SDValue InFlag;
11994   SDLoc dl(GA);  // ? function entry point might be better
11995   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11996                                    DAG.getNode(X86ISD::GlobalBaseReg,
11997                                                SDLoc(), PtrVT), InFlag);
11998   InFlag = Chain.getValue(1);
11999
12000   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12001 }
12002
12003 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12004 static SDValue
12005 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12006                                 const EVT PtrVT) {
12007   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12008                     X86::RAX, X86II::MO_TLSGD);
12009 }
12010
12011 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12012                                            SelectionDAG &DAG,
12013                                            const EVT PtrVT,
12014                                            bool is64Bit) {
12015   SDLoc dl(GA);
12016
12017   // Get the start address of the TLS block for this module.
12018   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12019       .getInfo<X86MachineFunctionInfo>();
12020   MFI->incNumLocalDynamicTLSAccesses();
12021
12022   SDValue Base;
12023   if (is64Bit) {
12024     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12025                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12026   } else {
12027     SDValue InFlag;
12028     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12029         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12030     InFlag = Chain.getValue(1);
12031     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12032                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12033   }
12034
12035   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12036   // of Base.
12037
12038   // Build x@dtpoff.
12039   unsigned char OperandFlags = X86II::MO_DTPOFF;
12040   unsigned WrapperKind = X86ISD::Wrapper;
12041   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12042                                            GA->getValueType(0),
12043                                            GA->getOffset(), OperandFlags);
12044   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12045
12046   // Add x@dtpoff with the base.
12047   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12048 }
12049
12050 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12051 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12052                                    const EVT PtrVT, TLSModel::Model model,
12053                                    bool is64Bit, bool isPIC) {
12054   SDLoc dl(GA);
12055
12056   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12057   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12058                                                          is64Bit ? 257 : 256));
12059
12060   SDValue ThreadPointer =
12061       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12062                   MachinePointerInfo(Ptr), false, false, false, 0);
12063
12064   unsigned char OperandFlags = 0;
12065   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12066   // initialexec.
12067   unsigned WrapperKind = X86ISD::Wrapper;
12068   if (model == TLSModel::LocalExec) {
12069     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12070   } else if (model == TLSModel::InitialExec) {
12071     if (is64Bit) {
12072       OperandFlags = X86II::MO_GOTTPOFF;
12073       WrapperKind = X86ISD::WrapperRIP;
12074     } else {
12075       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12076     }
12077   } else {
12078     llvm_unreachable("Unexpected model");
12079   }
12080
12081   // emit "addl x@ntpoff,%eax" (local exec)
12082   // or "addl x@indntpoff,%eax" (initial exec)
12083   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12084   SDValue TGA =
12085       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12086                                  GA->getOffset(), OperandFlags);
12087   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12088
12089   if (model == TLSModel::InitialExec) {
12090     if (isPIC && !is64Bit) {
12091       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12092                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12093                            Offset);
12094     }
12095
12096     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12097                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12098                          false, false, false, 0);
12099   }
12100
12101   // The address of the thread local variable is the add of the thread
12102   // pointer with the offset of the variable.
12103   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12104 }
12105
12106 SDValue
12107 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12108
12109   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12110   const GlobalValue *GV = GA->getGlobal();
12111   auto PtrVT = getPointerTy(DAG.getDataLayout());
12112
12113   if (Subtarget->isTargetELF()) {
12114     if (DAG.getTarget().Options.EmulatedTLS)
12115       return LowerToTLSEmulatedModel(GA, DAG);
12116     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12117     switch (model) {
12118       case TLSModel::GeneralDynamic:
12119         if (Subtarget->is64Bit())
12120           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12121         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12122       case TLSModel::LocalDynamic:
12123         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12124                                            Subtarget->is64Bit());
12125       case TLSModel::InitialExec:
12126       case TLSModel::LocalExec:
12127         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12128                                    DAG.getTarget().getRelocationModel() ==
12129                                        Reloc::PIC_);
12130     }
12131     llvm_unreachable("Unknown TLS model.");
12132   }
12133
12134   if (Subtarget->isTargetDarwin()) {
12135     // Darwin only has one model of TLS.  Lower to that.
12136     unsigned char OpFlag = 0;
12137     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12138                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12139
12140     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12141     // global base reg.
12142     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12143                  !Subtarget->is64Bit();
12144     if (PIC32)
12145       OpFlag = X86II::MO_TLVP_PIC_BASE;
12146     else
12147       OpFlag = X86II::MO_TLVP;
12148     SDLoc DL(Op);
12149     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12150                                                 GA->getValueType(0),
12151                                                 GA->getOffset(), OpFlag);
12152     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12153
12154     // With PIC32, the address is actually $g + Offset.
12155     if (PIC32)
12156       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12157                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12158                            Offset);
12159
12160     // Lowering the machine isd will make sure everything is in the right
12161     // location.
12162     SDValue Chain = DAG.getEntryNode();
12163     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12164     SDValue Args[] = { Chain, Offset };
12165     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12166
12167     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12168     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12169     MFI->setAdjustsStack(true);
12170
12171     // And our return value (tls address) is in the standard call return value
12172     // location.
12173     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12174     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12175   }
12176
12177   if (Subtarget->isTargetKnownWindowsMSVC() ||
12178       Subtarget->isTargetWindowsGNU()) {
12179     // Just use the implicit TLS architecture
12180     // Need to generate someting similar to:
12181     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12182     //                                  ; from TEB
12183     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12184     //   mov     rcx, qword [rdx+rcx*8]
12185     //   mov     eax, .tls$:tlsvar
12186     //   [rax+rcx] contains the address
12187     // Windows 64bit: gs:0x58
12188     // Windows 32bit: fs:__tls_array
12189
12190     SDLoc dl(GA);
12191     SDValue Chain = DAG.getEntryNode();
12192
12193     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12194     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12195     // use its literal value of 0x2C.
12196     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12197                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12198                                                              256)
12199                                         : Type::getInt32PtrTy(*DAG.getContext(),
12200                                                               257));
12201
12202     SDValue TlsArray = Subtarget->is64Bit()
12203                            ? DAG.getIntPtrConstant(0x58, dl)
12204                            : (Subtarget->isTargetWindowsGNU()
12205                                   ? DAG.getIntPtrConstant(0x2C, dl)
12206                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12207
12208     SDValue ThreadPointer =
12209         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12210                     false, false, 0);
12211
12212     SDValue res;
12213     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12214       res = ThreadPointer;
12215     } else {
12216       // Load the _tls_index variable
12217       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12218       if (Subtarget->is64Bit())
12219         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12220                              MachinePointerInfo(), MVT::i32, false, false,
12221                              false, 0);
12222       else
12223         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12224                           false, false, 0);
12225
12226       auto &DL = DAG.getDataLayout();
12227       SDValue Scale =
12228           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12229       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12230
12231       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12232     }
12233
12234     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12235                       false, 0);
12236
12237     // Get the offset of start of .tls section
12238     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12239                                              GA->getValueType(0),
12240                                              GA->getOffset(), X86II::MO_SECREL);
12241     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12242
12243     // The address of the thread local variable is the add of the thread
12244     // pointer with the offset of the variable.
12245     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12246   }
12247
12248   llvm_unreachable("TLS not implemented for this target.");
12249 }
12250
12251 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12252 /// and take a 2 x i32 value to shift plus a shift amount.
12253 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12254   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12255   MVT VT = Op.getSimpleValueType();
12256   unsigned VTBits = VT.getSizeInBits();
12257   SDLoc dl(Op);
12258   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12259   SDValue ShOpLo = Op.getOperand(0);
12260   SDValue ShOpHi = Op.getOperand(1);
12261   SDValue ShAmt  = Op.getOperand(2);
12262   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12263   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12264   // during isel.
12265   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12266                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12267   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12268                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12269                        : DAG.getConstant(0, dl, VT);
12270
12271   SDValue Tmp2, Tmp3;
12272   if (Op.getOpcode() == ISD::SHL_PARTS) {
12273     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12274     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12275   } else {
12276     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12277     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12278   }
12279
12280   // If the shift amount is larger or equal than the width of a part we can't
12281   // rely on the results of shld/shrd. Insert a test and select the appropriate
12282   // values for large shift amounts.
12283   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12284                                 DAG.getConstant(VTBits, dl, MVT::i8));
12285   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12286                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12287
12288   SDValue Hi, Lo;
12289   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12290   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12291   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12292
12293   if (Op.getOpcode() == ISD::SHL_PARTS) {
12294     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12295     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12296   } else {
12297     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12298     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12299   }
12300
12301   SDValue Ops[2] = { Lo, Hi };
12302   return DAG.getMergeValues(Ops, dl);
12303 }
12304
12305 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12306                                            SelectionDAG &DAG) const {
12307   SDValue Src = Op.getOperand(0);
12308   MVT SrcVT = Src.getSimpleValueType();
12309   MVT VT = Op.getSimpleValueType();
12310   SDLoc dl(Op);
12311
12312   if (SrcVT.isVector()) {
12313     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12314       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12315                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12316                          DAG.getUNDEF(SrcVT)));
12317     }
12318     if (SrcVT.getVectorElementType() == MVT::i1) {
12319       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12320       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12321                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12322     }
12323     return SDValue();
12324   }
12325
12326   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12327          "Unknown SINT_TO_FP to lower!");
12328
12329   // These are really Legal; return the operand so the caller accepts it as
12330   // Legal.
12331   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12332     return Op;
12333   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12334       Subtarget->is64Bit()) {
12335     return Op;
12336   }
12337
12338   unsigned Size = SrcVT.getSizeInBits()/8;
12339   MachineFunction &MF = DAG.getMachineFunction();
12340   auto PtrVT = getPointerTy(MF.getDataLayout());
12341   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12342   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12343   SDValue Chain = DAG.getStore(
12344       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12345       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12346       false, 0);
12347   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12348 }
12349
12350 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12351                                      SDValue StackSlot,
12352                                      SelectionDAG &DAG) const {
12353   // Build the FILD
12354   SDLoc DL(Op);
12355   SDVTList Tys;
12356   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12357   if (useSSE)
12358     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12359   else
12360     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12361
12362   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12363
12364   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12365   MachineMemOperand *MMO;
12366   if (FI) {
12367     int SSFI = FI->getIndex();
12368     MMO = DAG.getMachineFunction().getMachineMemOperand(
12369         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12370         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12371   } else {
12372     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12373     StackSlot = StackSlot.getOperand(1);
12374   }
12375   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12376   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12377                                            X86ISD::FILD, DL,
12378                                            Tys, Ops, SrcVT, MMO);
12379
12380   if (useSSE) {
12381     Chain = Result.getValue(1);
12382     SDValue InFlag = Result.getValue(2);
12383
12384     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12385     // shouldn't be necessary except that RFP cannot be live across
12386     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12387     MachineFunction &MF = DAG.getMachineFunction();
12388     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12389     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12390     auto PtrVT = getPointerTy(MF.getDataLayout());
12391     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12392     Tys = DAG.getVTList(MVT::Other);
12393     SDValue Ops[] = {
12394       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12395     };
12396     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12397         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12398         MachineMemOperand::MOStore, SSFISize, SSFISize);
12399
12400     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12401                                     Ops, Op.getValueType(), MMO);
12402     Result = DAG.getLoad(
12403         Op.getValueType(), DL, Chain, StackSlot,
12404         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12405         false, false, false, 0);
12406   }
12407
12408   return Result;
12409 }
12410
12411 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12412 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12413                                                SelectionDAG &DAG) const {
12414   // This algorithm is not obvious. Here it is what we're trying to output:
12415   /*
12416      movq       %rax,  %xmm0
12417      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12418      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12419      #ifdef __SSE3__
12420        haddpd   %xmm0, %xmm0
12421      #else
12422        pshufd   $0x4e, %xmm0, %xmm1
12423        addpd    %xmm1, %xmm0
12424      #endif
12425   */
12426
12427   SDLoc dl(Op);
12428   LLVMContext *Context = DAG.getContext();
12429
12430   // Build some magic constants.
12431   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12432   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12433   auto PtrVT = getPointerTy(DAG.getDataLayout());
12434   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12435
12436   SmallVector<Constant*,2> CV1;
12437   CV1.push_back(
12438     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12439                                       APInt(64, 0x4330000000000000ULL))));
12440   CV1.push_back(
12441     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12442                                       APInt(64, 0x4530000000000000ULL))));
12443   Constant *C1 = ConstantVector::get(CV1);
12444   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12445
12446   // Load the 64-bit value into an XMM register.
12447   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12448                             Op.getOperand(0));
12449   SDValue CLod0 =
12450       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12451                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12452                   false, false, false, 16);
12453   SDValue Unpck1 =
12454       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12455
12456   SDValue CLod1 =
12457       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12458                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12459                   false, false, false, 16);
12460   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12461   // TODO: Are there any fast-math-flags to propagate here?
12462   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12463   SDValue Result;
12464
12465   if (Subtarget->hasSSE3()) {
12466     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12467     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12468   } else {
12469     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12470     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12471                                            S2F, 0x4E, DAG);
12472     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12473                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12474   }
12475
12476   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12477                      DAG.getIntPtrConstant(0, dl));
12478 }
12479
12480 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12481 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12482                                                SelectionDAG &DAG) const {
12483   SDLoc dl(Op);
12484   // FP constant to bias correct the final result.
12485   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12486                                    MVT::f64);
12487
12488   // Load the 32-bit value into an XMM register.
12489   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12490                              Op.getOperand(0));
12491
12492   // Zero out the upper parts of the register.
12493   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12494
12495   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12496                      DAG.getBitcast(MVT::v2f64, Load),
12497                      DAG.getIntPtrConstant(0, dl));
12498
12499   // Or the load with the bias.
12500   SDValue Or = DAG.getNode(
12501       ISD::OR, dl, MVT::v2i64,
12502       DAG.getBitcast(MVT::v2i64,
12503                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12504       DAG.getBitcast(MVT::v2i64,
12505                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12506   Or =
12507       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12508                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12509
12510   // Subtract the bias.
12511   // TODO: Are there any fast-math-flags to propagate here?
12512   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12513
12514   // Handle final rounding.
12515   EVT DestVT = Op.getValueType();
12516
12517   if (DestVT.bitsLT(MVT::f64))
12518     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12519                        DAG.getIntPtrConstant(0, dl));
12520   if (DestVT.bitsGT(MVT::f64))
12521     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12522
12523   // Handle final rounding.
12524   return Sub;
12525 }
12526
12527 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12528                                      const X86Subtarget &Subtarget) {
12529   // The algorithm is the following:
12530   // #ifdef __SSE4_1__
12531   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12532   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12533   //                                 (uint4) 0x53000000, 0xaa);
12534   // #else
12535   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12536   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12537   // #endif
12538   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12539   //     return (float4) lo + fhi;
12540
12541   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12542   // reassociate the two FADDs, and if we do that, the algorithm fails
12543   // spectacularly (PR24512).
12544   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12545   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12546   // there's also the MachineCombiner reassociations happening on Machine IR.
12547   if (DAG.getTarget().Options.UnsafeFPMath)
12548     return SDValue();
12549
12550   SDLoc DL(Op);
12551   SDValue V = Op->getOperand(0);
12552   EVT VecIntVT = V.getValueType();
12553   bool Is128 = VecIntVT == MVT::v4i32;
12554   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12555   // If we convert to something else than the supported type, e.g., to v4f64,
12556   // abort early.
12557   if (VecFloatVT != Op->getValueType(0))
12558     return SDValue();
12559
12560   unsigned NumElts = VecIntVT.getVectorNumElements();
12561   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12562          "Unsupported custom type");
12563   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12564
12565   // In the #idef/#else code, we have in common:
12566   // - The vector of constants:
12567   // -- 0x4b000000
12568   // -- 0x53000000
12569   // - A shift:
12570   // -- v >> 16
12571
12572   // Create the splat vector for 0x4b000000.
12573   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12574   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12575                            CstLow, CstLow, CstLow, CstLow};
12576   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12577                                   makeArrayRef(&CstLowArray[0], NumElts));
12578   // Create the splat vector for 0x53000000.
12579   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12580   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12581                             CstHigh, CstHigh, CstHigh, CstHigh};
12582   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12583                                    makeArrayRef(&CstHighArray[0], NumElts));
12584
12585   // Create the right shift.
12586   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12587   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12588                              CstShift, CstShift, CstShift, CstShift};
12589   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12590                                     makeArrayRef(&CstShiftArray[0], NumElts));
12591   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12592
12593   SDValue Low, High;
12594   if (Subtarget.hasSSE41()) {
12595     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12596     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12597     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12598     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12599     // Low will be bitcasted right away, so do not bother bitcasting back to its
12600     // original type.
12601     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12602                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12603     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12604     //                                 (uint4) 0x53000000, 0xaa);
12605     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12606     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12607     // High will be bitcasted right away, so do not bother bitcasting back to
12608     // its original type.
12609     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12610                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12611   } else {
12612     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12613     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12614                                      CstMask, CstMask, CstMask);
12615     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12616     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12617     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12618
12619     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12620     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12621   }
12622
12623   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12624   SDValue CstFAdd = DAG.getConstantFP(
12625       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12626   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12627                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12628   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12629                                    makeArrayRef(&CstFAddArray[0], NumElts));
12630
12631   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12632   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12633   // TODO: Are there any fast-math-flags to propagate here?
12634   SDValue FHigh =
12635       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12636   //     return (float4) lo + fhi;
12637   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12638   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12639 }
12640
12641 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12642                                                SelectionDAG &DAG) const {
12643   SDValue N0 = Op.getOperand(0);
12644   MVT SVT = N0.getSimpleValueType();
12645   SDLoc dl(Op);
12646
12647   switch (SVT.SimpleTy) {
12648   default:
12649     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12650   case MVT::v4i8:
12651   case MVT::v4i16:
12652   case MVT::v8i8:
12653   case MVT::v8i16: {
12654     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12655     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12656                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12657   }
12658   case MVT::v4i32:
12659   case MVT::v8i32:
12660     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12661   case MVT::v16i8:
12662   case MVT::v16i16:
12663     if (Subtarget->hasAVX512())
12664       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12665                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12666   }
12667   llvm_unreachable(nullptr);
12668 }
12669
12670 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12671                                            SelectionDAG &DAG) const {
12672   SDValue N0 = Op.getOperand(0);
12673   SDLoc dl(Op);
12674   auto PtrVT = getPointerTy(DAG.getDataLayout());
12675
12676   if (Op.getValueType().isVector())
12677     return lowerUINT_TO_FP_vec(Op, DAG);
12678
12679   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12680   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12681   // the optimization here.
12682   if (DAG.SignBitIsZero(N0))
12683     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12684
12685   MVT SrcVT = N0.getSimpleValueType();
12686   MVT DstVT = Op.getSimpleValueType();
12687
12688   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12689       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12690     // Conversions from unsigned i32 to f32/f64 are legal,
12691     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12692     return Op;
12693   }
12694
12695   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12696     return LowerUINT_TO_FP_i64(Op, DAG);
12697   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12698     return LowerUINT_TO_FP_i32(Op, DAG);
12699   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12700     return SDValue();
12701
12702   // Make a 64-bit buffer, and use it to build an FILD.
12703   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12704   if (SrcVT == MVT::i32) {
12705     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12706     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12707     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12708                                   StackSlot, MachinePointerInfo(),
12709                                   false, false, 0);
12710     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12711                                   OffsetSlot, MachinePointerInfo(),
12712                                   false, false, 0);
12713     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12714     return Fild;
12715   }
12716
12717   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12718   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12719                                StackSlot, MachinePointerInfo(),
12720                                false, false, 0);
12721   // For i64 source, we need to add the appropriate power of 2 if the input
12722   // was negative.  This is the same as the optimization in
12723   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12724   // we must be careful to do the computation in x87 extended precision, not
12725   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12726   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12727   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12728       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12729       MachineMemOperand::MOLoad, 8, 8);
12730
12731   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12732   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12733   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12734                                          MVT::i64, MMO);
12735
12736   APInt FF(32, 0x5F800000ULL);
12737
12738   // Check whether the sign bit is set.
12739   SDValue SignSet = DAG.getSetCC(
12740       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12741       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12742
12743   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12744   SDValue FudgePtr = DAG.getConstantPool(
12745       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12746
12747   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12748   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12749   SDValue Four = DAG.getIntPtrConstant(4, dl);
12750   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12751                                Zero, Four);
12752   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12753
12754   // Load the value out, extending it from f32 to f80.
12755   // FIXME: Avoid the extend by constructing the right constant pool?
12756   SDValue Fudge = DAG.getExtLoad(
12757       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12758       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12759       false, false, false, 4);
12760   // Extend everything to 80 bits to force it to be done on x87.
12761   // TODO: Are there any fast-math-flags to propagate here?
12762   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12763   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12764                      DAG.getIntPtrConstant(0, dl));
12765 }
12766
12767 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12768 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12769 // just return an <SDValue(), SDValue()> pair.
12770 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12771 // to i16, i32 or i64, and we lower it to a legal sequence.
12772 // If lowered to the final integer result we return a <result, SDValue()> pair.
12773 // Otherwise we lower it to a sequence ending with a FIST, return a
12774 // <FIST, StackSlot> pair, and the caller is responsible for loading
12775 // the final integer result from StackSlot.
12776 std::pair<SDValue,SDValue>
12777 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12778                                    bool IsSigned, bool IsReplace) const {
12779   SDLoc DL(Op);
12780
12781   EVT DstTy = Op.getValueType();
12782   EVT TheVT = Op.getOperand(0).getValueType();
12783   auto PtrVT = getPointerTy(DAG.getDataLayout());
12784
12785   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12786     // f16 must be promoted before using the lowering in this routine.
12787     // fp128 does not use this lowering.
12788     return std::make_pair(SDValue(), SDValue());
12789   }
12790
12791   // If using FIST to compute an unsigned i64, we'll need some fixup
12792   // to handle values above the maximum signed i64.  A FIST is always
12793   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12794   bool UnsignedFixup = !IsSigned &&
12795                        DstTy == MVT::i64 &&
12796                        (!Subtarget->is64Bit() ||
12797                         !isScalarFPTypeInSSEReg(TheVT));
12798
12799   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12800     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12801     // The low 32 bits of the fist result will have the correct uint32 result.
12802     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12803     DstTy = MVT::i64;
12804   }
12805
12806   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12807          DstTy.getSimpleVT() >= MVT::i16 &&
12808          "Unknown FP_TO_INT to lower!");
12809
12810   // These are really Legal.
12811   if (DstTy == MVT::i32 &&
12812       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12813     return std::make_pair(SDValue(), SDValue());
12814   if (Subtarget->is64Bit() &&
12815       DstTy == MVT::i64 &&
12816       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12817     return std::make_pair(SDValue(), SDValue());
12818
12819   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12820   // stack slot.
12821   MachineFunction &MF = DAG.getMachineFunction();
12822   unsigned MemSize = DstTy.getSizeInBits()/8;
12823   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12824   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12825
12826   unsigned Opc;
12827   switch (DstTy.getSimpleVT().SimpleTy) {
12828   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12829   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12830   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12831   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12832   }
12833
12834   SDValue Chain = DAG.getEntryNode();
12835   SDValue Value = Op.getOperand(0);
12836   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12837
12838   if (UnsignedFixup) {
12839     //
12840     // Conversion to unsigned i64 is implemented with a select,
12841     // depending on whether the source value fits in the range
12842     // of a signed i64.  Let Thresh be the FP equivalent of
12843     // 0x8000000000000000ULL.
12844     //
12845     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12846     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12847     //  Fist-to-mem64 FistSrc
12848     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12849     //  to XOR'ing the high 32 bits with Adjust.
12850     //
12851     // Being a power of 2, Thresh is exactly representable in all FP formats.
12852     // For X87 we'd like to use the smallest FP type for this constant, but
12853     // for DAG type consistency we have to match the FP operand type.
12854
12855     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12856     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12857     bool LosesInfo = false;
12858     if (TheVT == MVT::f64)
12859       // The rounding mode is irrelevant as the conversion should be exact.
12860       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12861                               &LosesInfo);
12862     else if (TheVT == MVT::f80)
12863       Status = Thresh.convert(APFloat::x87DoubleExtended,
12864                               APFloat::rmNearestTiesToEven, &LosesInfo);
12865
12866     assert(Status == APFloat::opOK && !LosesInfo &&
12867            "FP conversion should have been exact");
12868
12869     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12870
12871     SDValue Cmp = DAG.getSetCC(DL,
12872                                getSetCCResultType(DAG.getDataLayout(),
12873                                                   *DAG.getContext(), TheVT),
12874                                Value, ThreshVal, ISD::SETLT);
12875     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12876                            DAG.getConstant(0, DL, MVT::i32),
12877                            DAG.getConstant(0x80000000, DL, MVT::i32));
12878     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12879     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12880                                               *DAG.getContext(), TheVT),
12881                        Value, ThreshVal, ISD::SETLT);
12882     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12883   }
12884
12885   // FIXME This causes a redundant load/store if the SSE-class value is already
12886   // in memory, such as if it is on the callstack.
12887   if (isScalarFPTypeInSSEReg(TheVT)) {
12888     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12889     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12890                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12891                          false, 0);
12892     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12893     SDValue Ops[] = {
12894       Chain, StackSlot, DAG.getValueType(TheVT)
12895     };
12896
12897     MachineMemOperand *MMO =
12898         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12899                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12900     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12901     Chain = Value.getValue(1);
12902     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12903     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12904   }
12905
12906   MachineMemOperand *MMO =
12907       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12908                               MachineMemOperand::MOStore, MemSize, MemSize);
12909
12910   if (UnsignedFixup) {
12911
12912     // Insert the FIST, load its result as two i32's,
12913     // and XOR the high i32 with Adjust.
12914
12915     SDValue FistOps[] = { Chain, Value, StackSlot };
12916     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12917                                            FistOps, DstTy, MMO);
12918
12919     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12920                                 MachinePointerInfo(),
12921                                 false, false, false, 0);
12922     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12923                                    DAG.getConstant(4, DL, PtrVT));
12924
12925     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12926                                  MachinePointerInfo(),
12927                                  false, false, false, 0);
12928     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12929
12930     if (Subtarget->is64Bit()) {
12931       // Join High32 and Low32 into a 64-bit result.
12932       // (High32 << 32) | Low32
12933       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12934       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12935       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12936                            DAG.getConstant(32, DL, MVT::i8));
12937       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12938       return std::make_pair(Result, SDValue());
12939     }
12940
12941     SDValue ResultOps[] = { Low32, High32 };
12942
12943     SDValue pair = IsReplace
12944       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12945       : DAG.getMergeValues(ResultOps, DL);
12946     return std::make_pair(pair, SDValue());
12947   } else {
12948     // Build the FP_TO_INT*_IN_MEM
12949     SDValue Ops[] = { Chain, Value, StackSlot };
12950     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12951                                            Ops, DstTy, MMO);
12952     return std::make_pair(FIST, StackSlot);
12953   }
12954 }
12955
12956 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12957                               const X86Subtarget *Subtarget) {
12958   MVT VT = Op->getSimpleValueType(0);
12959   SDValue In = Op->getOperand(0);
12960   MVT InVT = In.getSimpleValueType();
12961   SDLoc dl(Op);
12962
12963   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12964     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12965
12966   // Optimize vectors in AVX mode:
12967   //
12968   //   v8i16 -> v8i32
12969   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12970   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12971   //   Concat upper and lower parts.
12972   //
12973   //   v4i32 -> v4i64
12974   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12975   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12976   //   Concat upper and lower parts.
12977   //
12978
12979   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12980       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12981       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12982     return SDValue();
12983
12984   if (Subtarget->hasInt256())
12985     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12986
12987   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12988   SDValue Undef = DAG.getUNDEF(InVT);
12989   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12990   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12991   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12992
12993   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12994                              VT.getVectorNumElements()/2);
12995
12996   OpLo = DAG.getBitcast(HVT, OpLo);
12997   OpHi = DAG.getBitcast(HVT, OpHi);
12998
12999   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13000 }
13001
13002 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13003                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13004   MVT VT = Op->getSimpleValueType(0);
13005   SDValue In = Op->getOperand(0);
13006   MVT InVT = In.getSimpleValueType();
13007   SDLoc DL(Op);
13008   unsigned int NumElts = VT.getVectorNumElements();
13009   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13010     return SDValue();
13011
13012   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13013     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13014
13015   assert(InVT.getVectorElementType() == MVT::i1);
13016   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13017   SDValue One =
13018    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13019   SDValue Zero =
13020    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13021
13022   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13023   if (VT.is512BitVector())
13024     return V;
13025   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13026 }
13027
13028 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13029                                SelectionDAG &DAG) {
13030   if (Subtarget->hasFp256())
13031     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13032       return Res;
13033
13034   return SDValue();
13035 }
13036
13037 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13038                                 SelectionDAG &DAG) {
13039   SDLoc DL(Op);
13040   MVT VT = Op.getSimpleValueType();
13041   SDValue In = Op.getOperand(0);
13042   MVT SVT = In.getSimpleValueType();
13043
13044   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13045     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13046
13047   if (Subtarget->hasFp256())
13048     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13049       return Res;
13050
13051   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13052          VT.getVectorNumElements() != SVT.getVectorNumElements());
13053   return SDValue();
13054 }
13055
13056 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13057   SDLoc DL(Op);
13058   MVT VT = Op.getSimpleValueType();
13059   SDValue In = Op.getOperand(0);
13060   MVT InVT = In.getSimpleValueType();
13061
13062   if (VT == MVT::i1) {
13063     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13064            "Invalid scalar TRUNCATE operation");
13065     if (InVT.getSizeInBits() >= 32)
13066       return SDValue();
13067     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13068     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13069   }
13070   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13071          "Invalid TRUNCATE operation");
13072
13073   // move vector to mask - truncate solution for SKX
13074   if (VT.getVectorElementType() == MVT::i1) {
13075     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13076         Subtarget->hasBWI())
13077       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13078     if ((InVT.is256BitVector() || InVT.is128BitVector())
13079         && InVT.getScalarSizeInBits() <= 16 &&
13080         Subtarget->hasBWI() && Subtarget->hasVLX())
13081       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13082     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13083         Subtarget->hasDQI())
13084       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13085     if ((InVT.is256BitVector() || InVT.is128BitVector())
13086         && InVT.getScalarSizeInBits() >= 32 &&
13087         Subtarget->hasDQI() && Subtarget->hasVLX())
13088       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13089   }
13090
13091   if (VT.getVectorElementType() == MVT::i1) {
13092     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13093     unsigned NumElts = InVT.getVectorNumElements();
13094     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13095     if (InVT.getSizeInBits() < 512) {
13096       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13097       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13098       InVT = ExtVT;
13099     }
13100
13101     SDValue OneV =
13102      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13103     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13104     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13105   }
13106
13107   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13108   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13109       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13110     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13111
13112   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13113     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13114     if (Subtarget->hasInt256()) {
13115       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13116       In = DAG.getBitcast(MVT::v8i32, In);
13117       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13118                                 ShufMask);
13119       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13120                          DAG.getIntPtrConstant(0, DL));
13121     }
13122
13123     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13124                                DAG.getIntPtrConstant(0, DL));
13125     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13126                                DAG.getIntPtrConstant(2, DL));
13127     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13128     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13129     static const int ShufMask[] = {0, 2, 4, 6};
13130     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13131   }
13132
13133   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13134     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13135     if (Subtarget->hasInt256()) {
13136       In = DAG.getBitcast(MVT::v32i8, In);
13137
13138       SmallVector<SDValue,32> pshufbMask;
13139       for (unsigned i = 0; i < 2; ++i) {
13140         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13141         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13142         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13143         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13144         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13145         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13146         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13147         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13148         for (unsigned j = 0; j < 8; ++j)
13149           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13150       }
13151       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13152       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13153       In = DAG.getBitcast(MVT::v4i64, In);
13154
13155       static const int ShufMask[] = {0,  2,  -1,  -1};
13156       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13157                                 &ShufMask[0]);
13158       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13159                        DAG.getIntPtrConstant(0, DL));
13160       return DAG.getBitcast(VT, In);
13161     }
13162
13163     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13164                                DAG.getIntPtrConstant(0, DL));
13165
13166     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13167                                DAG.getIntPtrConstant(4, DL));
13168
13169     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13170     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13171
13172     // The PSHUFB mask:
13173     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13174                                    -1, -1, -1, -1, -1, -1, -1, -1};
13175
13176     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13177     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13178     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13179
13180     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13181     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13182
13183     // The MOVLHPS Mask:
13184     static const int ShufMask2[] = {0, 1, 4, 5};
13185     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13186     return DAG.getBitcast(MVT::v8i16, res);
13187   }
13188
13189   // Handle truncation of V256 to V128 using shuffles.
13190   if (!VT.is128BitVector() || !InVT.is256BitVector())
13191     return SDValue();
13192
13193   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13194
13195   unsigned NumElems = VT.getVectorNumElements();
13196   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13197
13198   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13199   // Prepare truncation shuffle mask
13200   for (unsigned i = 0; i != NumElems; ++i)
13201     MaskVec[i] = i * 2;
13202   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13203                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13204   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13205                      DAG.getIntPtrConstant(0, DL));
13206 }
13207
13208 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13209                                            SelectionDAG &DAG) const {
13210   assert(!Op.getSimpleValueType().isVector());
13211
13212   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13213     /*IsSigned=*/ true, /*IsReplace=*/ false);
13214   SDValue FIST = Vals.first, StackSlot = Vals.second;
13215   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13216   if (!FIST.getNode())
13217     return Op;
13218
13219   if (StackSlot.getNode())
13220     // Load the result.
13221     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13222                        FIST, StackSlot, MachinePointerInfo(),
13223                        false, false, false, 0);
13224
13225   // The node is the result.
13226   return FIST;
13227 }
13228
13229 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13230                                            SelectionDAG &DAG) const {
13231   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13232     /*IsSigned=*/ false, /*IsReplace=*/ false);
13233   SDValue FIST = Vals.first, StackSlot = Vals.second;
13234   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13235   if (!FIST.getNode())
13236     return Op;
13237
13238   if (StackSlot.getNode())
13239     // Load the result.
13240     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13241                        FIST, StackSlot, MachinePointerInfo(),
13242                        false, false, false, 0);
13243
13244   // The node is the result.
13245   return FIST;
13246 }
13247
13248 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13249   SDLoc DL(Op);
13250   MVT VT = Op.getSimpleValueType();
13251   SDValue In = Op.getOperand(0);
13252   MVT SVT = In.getSimpleValueType();
13253
13254   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13255
13256   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13257                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13258                                  In, DAG.getUNDEF(SVT)));
13259 }
13260
13261 /// The only differences between FABS and FNEG are the mask and the logic op.
13262 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13263 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13264   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13265          "Wrong opcode for lowering FABS or FNEG.");
13266
13267   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13268
13269   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13270   // into an FNABS. We'll lower the FABS after that if it is still in use.
13271   if (IsFABS)
13272     for (SDNode *User : Op->uses())
13273       if (User->getOpcode() == ISD::FNEG)
13274         return Op;
13275
13276   SDLoc dl(Op);
13277   MVT VT = Op.getSimpleValueType();
13278
13279   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13280   // decide if we should generate a 16-byte constant mask when we only need 4 or
13281   // 8 bytes for the scalar case.
13282
13283   MVT LogicVT;
13284   MVT EltVT;
13285   unsigned NumElts;
13286
13287   if (VT.isVector()) {
13288     LogicVT = VT;
13289     EltVT = VT.getVectorElementType();
13290     NumElts = VT.getVectorNumElements();
13291   } else {
13292     // There are no scalar bitwise logical SSE/AVX instructions, so we
13293     // generate a 16-byte vector constant and logic op even for the scalar case.
13294     // Using a 16-byte mask allows folding the load of the mask with
13295     // the logic op, so it can save (~4 bytes) on code size.
13296     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13297     EltVT = VT;
13298     NumElts = (VT == MVT::f64) ? 2 : 4;
13299   }
13300
13301   unsigned EltBits = EltVT.getSizeInBits();
13302   LLVMContext *Context = DAG.getContext();
13303   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13304   APInt MaskElt =
13305     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13306   Constant *C = ConstantInt::get(*Context, MaskElt);
13307   C = ConstantVector::getSplat(NumElts, C);
13308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13309   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13310   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13311   SDValue Mask =
13312       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13313                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13314                   false, false, false, Alignment);
13315
13316   SDValue Op0 = Op.getOperand(0);
13317   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13318   unsigned LogicOp =
13319     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13320   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13321
13322   if (VT.isVector())
13323     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13324
13325   // For the scalar case extend to a 128-bit vector, perform the logic op,
13326   // and extract the scalar result back out.
13327   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13328   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13329   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13330                      DAG.getIntPtrConstant(0, dl));
13331 }
13332
13333 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13335   LLVMContext *Context = DAG.getContext();
13336   SDValue Op0 = Op.getOperand(0);
13337   SDValue Op1 = Op.getOperand(1);
13338   SDLoc dl(Op);
13339   MVT VT = Op.getSimpleValueType();
13340   MVT SrcVT = Op1.getSimpleValueType();
13341
13342   // If second operand is smaller, extend it first.
13343   if (SrcVT.bitsLT(VT)) {
13344     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13345     SrcVT = VT;
13346   }
13347   // And if it is bigger, shrink it first.
13348   if (SrcVT.bitsGT(VT)) {
13349     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13350     SrcVT = VT;
13351   }
13352
13353   // At this point the operands and the result should have the same
13354   // type, and that won't be f80 since that is not custom lowered.
13355
13356   const fltSemantics &Sem =
13357       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13358   const unsigned SizeInBits = VT.getSizeInBits();
13359
13360   SmallVector<Constant *, 4> CV(
13361       VT == MVT::f64 ? 2 : 4,
13362       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13363
13364   // First, clear all bits but the sign bit from the second operand (sign).
13365   CV[0] = ConstantFP::get(*Context,
13366                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13367   Constant *C = ConstantVector::get(CV);
13368   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13369   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13370
13371   // Perform all logic operations as 16-byte vectors because there are no
13372   // scalar FP logic instructions in SSE. This allows load folding of the
13373   // constants into the logic instructions.
13374   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13375   SDValue Mask1 =
13376       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13377                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13378                   false, false, false, 16);
13379   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13380   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13381
13382   // Next, clear the sign bit from the first operand (magnitude).
13383   // If it's a constant, we can clear it here.
13384   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13385     APFloat APF = Op0CN->getValueAPF();
13386     // If the magnitude is a positive zero, the sign bit alone is enough.
13387     if (APF.isPosZero())
13388       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13389                          DAG.getIntPtrConstant(0, dl));
13390     APF.clearSign();
13391     CV[0] = ConstantFP::get(*Context, APF);
13392   } else {
13393     CV[0] = ConstantFP::get(
13394         *Context,
13395         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13396   }
13397   C = ConstantVector::get(CV);
13398   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13399   SDValue Val =
13400       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13401                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13402                   false, false, false, 16);
13403   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13404   if (!isa<ConstantFPSDNode>(Op0)) {
13405     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13406     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13407   }
13408   // OR the magnitude value with the sign bit.
13409   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13410   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13411                      DAG.getIntPtrConstant(0, dl));
13412 }
13413
13414 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13415   SDValue N0 = Op.getOperand(0);
13416   SDLoc dl(Op);
13417   MVT VT = Op.getSimpleValueType();
13418
13419   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13420   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13421                                   DAG.getConstant(1, dl, VT));
13422   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13423 }
13424
13425 // Check whether an OR'd tree is PTEST-able.
13426 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13427                                       SelectionDAG &DAG) {
13428   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13429
13430   if (!Subtarget->hasSSE41())
13431     return SDValue();
13432
13433   if (!Op->hasOneUse())
13434     return SDValue();
13435
13436   SDNode *N = Op.getNode();
13437   SDLoc DL(N);
13438
13439   SmallVector<SDValue, 8> Opnds;
13440   DenseMap<SDValue, unsigned> VecInMap;
13441   SmallVector<SDValue, 8> VecIns;
13442   EVT VT = MVT::Other;
13443
13444   // Recognize a special case where a vector is casted into wide integer to
13445   // test all 0s.
13446   Opnds.push_back(N->getOperand(0));
13447   Opnds.push_back(N->getOperand(1));
13448
13449   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13450     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13451     // BFS traverse all OR'd operands.
13452     if (I->getOpcode() == ISD::OR) {
13453       Opnds.push_back(I->getOperand(0));
13454       Opnds.push_back(I->getOperand(1));
13455       // Re-evaluate the number of nodes to be traversed.
13456       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13457       continue;
13458     }
13459
13460     // Quit if a non-EXTRACT_VECTOR_ELT
13461     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13462       return SDValue();
13463
13464     // Quit if without a constant index.
13465     SDValue Idx = I->getOperand(1);
13466     if (!isa<ConstantSDNode>(Idx))
13467       return SDValue();
13468
13469     SDValue ExtractedFromVec = I->getOperand(0);
13470     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13471     if (M == VecInMap.end()) {
13472       VT = ExtractedFromVec.getValueType();
13473       // Quit if not 128/256-bit vector.
13474       if (!VT.is128BitVector() && !VT.is256BitVector())
13475         return SDValue();
13476       // Quit if not the same type.
13477       if (VecInMap.begin() != VecInMap.end() &&
13478           VT != VecInMap.begin()->first.getValueType())
13479         return SDValue();
13480       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13481       VecIns.push_back(ExtractedFromVec);
13482     }
13483     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13484   }
13485
13486   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13487          "Not extracted from 128-/256-bit vector.");
13488
13489   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13490
13491   for (DenseMap<SDValue, unsigned>::const_iterator
13492         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13493     // Quit if not all elements are used.
13494     if (I->second != FullMask)
13495       return SDValue();
13496   }
13497
13498   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13499
13500   // Cast all vectors into TestVT for PTEST.
13501   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13502     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13503
13504   // If more than one full vectors are evaluated, OR them first before PTEST.
13505   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13506     // Each iteration will OR 2 nodes and append the result until there is only
13507     // 1 node left, i.e. the final OR'd value of all vectors.
13508     SDValue LHS = VecIns[Slot];
13509     SDValue RHS = VecIns[Slot + 1];
13510     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13511   }
13512
13513   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13514                      VecIns.back(), VecIns.back());
13515 }
13516
13517 /// \brief return true if \c Op has a use that doesn't just read flags.
13518 static bool hasNonFlagsUse(SDValue Op) {
13519   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13520        ++UI) {
13521     SDNode *User = *UI;
13522     unsigned UOpNo = UI.getOperandNo();
13523     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13524       // Look pass truncate.
13525       UOpNo = User->use_begin().getOperandNo();
13526       User = *User->use_begin();
13527     }
13528
13529     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13530         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13531       return true;
13532   }
13533   return false;
13534 }
13535
13536 /// Emit nodes that will be selected as "test Op0,Op0", or something
13537 /// equivalent.
13538 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13539                                     SelectionDAG &DAG) const {
13540   if (Op.getValueType() == MVT::i1) {
13541     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13542     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13543                        DAG.getConstant(0, dl, MVT::i8));
13544   }
13545   // CF and OF aren't always set the way we want. Determine which
13546   // of these we need.
13547   bool NeedCF = false;
13548   bool NeedOF = false;
13549   switch (X86CC) {
13550   default: break;
13551   case X86::COND_A: case X86::COND_AE:
13552   case X86::COND_B: case X86::COND_BE:
13553     NeedCF = true;
13554     break;
13555   case X86::COND_G: case X86::COND_GE:
13556   case X86::COND_L: case X86::COND_LE:
13557   case X86::COND_O: case X86::COND_NO: {
13558     // Check if we really need to set the
13559     // Overflow flag. If NoSignedWrap is present
13560     // that is not actually needed.
13561     switch (Op->getOpcode()) {
13562     case ISD::ADD:
13563     case ISD::SUB:
13564     case ISD::MUL:
13565     case ISD::SHL: {
13566       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13567       if (BinNode->Flags.hasNoSignedWrap())
13568         break;
13569     }
13570     default:
13571       NeedOF = true;
13572       break;
13573     }
13574     break;
13575   }
13576   }
13577   // See if we can use the EFLAGS value from the operand instead of
13578   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13579   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13580   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13581     // Emit a CMP with 0, which is the TEST pattern.
13582     //if (Op.getValueType() == MVT::i1)
13583     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13584     //                     DAG.getConstant(0, MVT::i1));
13585     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13586                        DAG.getConstant(0, dl, Op.getValueType()));
13587   }
13588   unsigned Opcode = 0;
13589   unsigned NumOperands = 0;
13590
13591   // Truncate operations may prevent the merge of the SETCC instruction
13592   // and the arithmetic instruction before it. Attempt to truncate the operands
13593   // of the arithmetic instruction and use a reduced bit-width instruction.
13594   bool NeedTruncation = false;
13595   SDValue ArithOp = Op;
13596   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13597     SDValue Arith = Op->getOperand(0);
13598     // Both the trunc and the arithmetic op need to have one user each.
13599     if (Arith->hasOneUse())
13600       switch (Arith.getOpcode()) {
13601         default: break;
13602         case ISD::ADD:
13603         case ISD::SUB:
13604         case ISD::AND:
13605         case ISD::OR:
13606         case ISD::XOR: {
13607           NeedTruncation = true;
13608           ArithOp = Arith;
13609         }
13610       }
13611   }
13612
13613   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13614   // which may be the result of a CAST.  We use the variable 'Op', which is the
13615   // non-casted variable when we check for possible users.
13616   switch (ArithOp.getOpcode()) {
13617   case ISD::ADD:
13618     // Due to an isel shortcoming, be conservative if this add is likely to be
13619     // selected as part of a load-modify-store instruction. When the root node
13620     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13621     // uses of other nodes in the match, such as the ADD in this case. This
13622     // leads to the ADD being left around and reselected, with the result being
13623     // two adds in the output.  Alas, even if none our users are stores, that
13624     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13625     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13626     // climbing the DAG back to the root, and it doesn't seem to be worth the
13627     // effort.
13628     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13629          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13630       if (UI->getOpcode() != ISD::CopyToReg &&
13631           UI->getOpcode() != ISD::SETCC &&
13632           UI->getOpcode() != ISD::STORE)
13633         goto default_case;
13634
13635     if (ConstantSDNode *C =
13636         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13637       // An add of one will be selected as an INC.
13638       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13639         Opcode = X86ISD::INC;
13640         NumOperands = 1;
13641         break;
13642       }
13643
13644       // An add of negative one (subtract of one) will be selected as a DEC.
13645       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13646         Opcode = X86ISD::DEC;
13647         NumOperands = 1;
13648         break;
13649       }
13650     }
13651
13652     // Otherwise use a regular EFLAGS-setting add.
13653     Opcode = X86ISD::ADD;
13654     NumOperands = 2;
13655     break;
13656   case ISD::SHL:
13657   case ISD::SRL:
13658     // If we have a constant logical shift that's only used in a comparison
13659     // against zero turn it into an equivalent AND. This allows turning it into
13660     // a TEST instruction later.
13661     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13662         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13663       EVT VT = Op.getValueType();
13664       unsigned BitWidth = VT.getSizeInBits();
13665       unsigned ShAmt = Op->getConstantOperandVal(1);
13666       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13667         break;
13668       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13669                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13670                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13671       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13672         break;
13673       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13674                                 DAG.getConstant(Mask, dl, VT));
13675       DAG.ReplaceAllUsesWith(Op, New);
13676       Op = New;
13677     }
13678     break;
13679
13680   case ISD::AND:
13681     // If the primary and result isn't used, don't bother using X86ISD::AND,
13682     // because a TEST instruction will be better.
13683     if (!hasNonFlagsUse(Op))
13684       break;
13685     // FALL THROUGH
13686   case ISD::SUB:
13687   case ISD::OR:
13688   case ISD::XOR:
13689     // Due to the ISEL shortcoming noted above, be conservative if this op is
13690     // likely to be selected as part of a load-modify-store instruction.
13691     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13692            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13693       if (UI->getOpcode() == ISD::STORE)
13694         goto default_case;
13695
13696     // Otherwise use a regular EFLAGS-setting instruction.
13697     switch (ArithOp.getOpcode()) {
13698     default: llvm_unreachable("unexpected operator!");
13699     case ISD::SUB: Opcode = X86ISD::SUB; break;
13700     case ISD::XOR: Opcode = X86ISD::XOR; break;
13701     case ISD::AND: Opcode = X86ISD::AND; break;
13702     case ISD::OR: {
13703       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13704         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13705         if (EFLAGS.getNode())
13706           return EFLAGS;
13707       }
13708       Opcode = X86ISD::OR;
13709       break;
13710     }
13711     }
13712
13713     NumOperands = 2;
13714     break;
13715   case X86ISD::ADD:
13716   case X86ISD::SUB:
13717   case X86ISD::INC:
13718   case X86ISD::DEC:
13719   case X86ISD::OR:
13720   case X86ISD::XOR:
13721   case X86ISD::AND:
13722     return SDValue(Op.getNode(), 1);
13723   default:
13724   default_case:
13725     break;
13726   }
13727
13728   // If we found that truncation is beneficial, perform the truncation and
13729   // update 'Op'.
13730   if (NeedTruncation) {
13731     EVT VT = Op.getValueType();
13732     SDValue WideVal = Op->getOperand(0);
13733     EVT WideVT = WideVal.getValueType();
13734     unsigned ConvertedOp = 0;
13735     // Use a target machine opcode to prevent further DAGCombine
13736     // optimizations that may separate the arithmetic operations
13737     // from the setcc node.
13738     switch (WideVal.getOpcode()) {
13739       default: break;
13740       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13741       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13742       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13743       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13744       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13745     }
13746
13747     if (ConvertedOp) {
13748       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13749       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13750         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13751         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13752         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13753       }
13754     }
13755   }
13756
13757   if (Opcode == 0)
13758     // Emit a CMP with 0, which is the TEST pattern.
13759     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13760                        DAG.getConstant(0, dl, Op.getValueType()));
13761
13762   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13763   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13764
13765   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13766   DAG.ReplaceAllUsesWith(Op, New);
13767   return SDValue(New.getNode(), 1);
13768 }
13769
13770 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13771 /// equivalent.
13772 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13773                                    SDLoc dl, SelectionDAG &DAG) const {
13774   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13775     if (C->getAPIntValue() == 0)
13776       return EmitTest(Op0, X86CC, dl, DAG);
13777
13778      if (Op0.getValueType() == MVT::i1)
13779        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13780   }
13781
13782   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13783        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13784     // Do the comparison at i32 if it's smaller, besides the Atom case.
13785     // This avoids subregister aliasing issues. Keep the smaller reference
13786     // if we're optimizing for size, however, as that'll allow better folding
13787     // of memory operations.
13788     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13789         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13790         !Subtarget->isAtom()) {
13791       unsigned ExtendOp =
13792           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13793       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13794       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13795     }
13796     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13797     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13798     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13799                               Op0, Op1);
13800     return SDValue(Sub.getNode(), 1);
13801   }
13802   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13803 }
13804
13805 /// Convert a comparison if required by the subtarget.
13806 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13807                                                  SelectionDAG &DAG) const {
13808   // If the subtarget does not support the FUCOMI instruction, floating-point
13809   // comparisons have to be converted.
13810   if (Subtarget->hasCMov() ||
13811       Cmp.getOpcode() != X86ISD::CMP ||
13812       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13813       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13814     return Cmp;
13815
13816   // The instruction selector will select an FUCOM instruction instead of
13817   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13818   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13819   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13820   SDLoc dl(Cmp);
13821   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13822   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13823   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13824                             DAG.getConstant(8, dl, MVT::i8));
13825   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13826   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13827 }
13828
13829 /// The minimum architected relative accuracy is 2^-12. We need one
13830 /// Newton-Raphson step to have a good float result (24 bits of precision).
13831 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13832                                             DAGCombinerInfo &DCI,
13833                                             unsigned &RefinementSteps,
13834                                             bool &UseOneConstNR) const {
13835   EVT VT = Op.getValueType();
13836   const char *RecipOp;
13837
13838   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13839   // TODO: Add support for AVX512 (v16f32).
13840   // It is likely not profitable to do this for f64 because a double-precision
13841   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13842   // instructions: convert to single, rsqrtss, convert back to double, refine
13843   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13844   // along with FMA, this could be a throughput win.
13845   if (VT == MVT::f32 && Subtarget->hasSSE1())
13846     RecipOp = "sqrtf";
13847   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13848            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13849     RecipOp = "vec-sqrtf";
13850   else
13851     return SDValue();
13852
13853   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13854   if (!Recips.isEnabled(RecipOp))
13855     return SDValue();
13856
13857   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13858   UseOneConstNR = false;
13859   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13860 }
13861
13862 /// The minimum architected relative accuracy is 2^-12. We need one
13863 /// Newton-Raphson step to have a good float result (24 bits of precision).
13864 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13865                                             DAGCombinerInfo &DCI,
13866                                             unsigned &RefinementSteps) const {
13867   EVT VT = Op.getValueType();
13868   const char *RecipOp;
13869
13870   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13871   // TODO: Add support for AVX512 (v16f32).
13872   // It is likely not profitable to do this for f64 because a double-precision
13873   // reciprocal estimate with refinement on x86 prior to FMA requires
13874   // 15 instructions: convert to single, rcpss, convert back to double, refine
13875   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13876   // along with FMA, this could be a throughput win.
13877   if (VT == MVT::f32 && Subtarget->hasSSE1())
13878     RecipOp = "divf";
13879   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13880            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13881     RecipOp = "vec-divf";
13882   else
13883     return SDValue();
13884
13885   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13886   if (!Recips.isEnabled(RecipOp))
13887     return SDValue();
13888
13889   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13890   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13891 }
13892
13893 /// If we have at least two divisions that use the same divisor, convert to
13894 /// multplication by a reciprocal. This may need to be adjusted for a given
13895 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13896 /// This is because we still need one division to calculate the reciprocal and
13897 /// then we need two multiplies by that reciprocal as replacements for the
13898 /// original divisions.
13899 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13900   return 2;
13901 }
13902
13903 static bool isAllOnes(SDValue V) {
13904   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13905   return C && C->isAllOnesValue();
13906 }
13907
13908 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13909 /// if it's possible.
13910 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13911                                      SDLoc dl, SelectionDAG &DAG) const {
13912   SDValue Op0 = And.getOperand(0);
13913   SDValue Op1 = And.getOperand(1);
13914   if (Op0.getOpcode() == ISD::TRUNCATE)
13915     Op0 = Op0.getOperand(0);
13916   if (Op1.getOpcode() == ISD::TRUNCATE)
13917     Op1 = Op1.getOperand(0);
13918
13919   SDValue LHS, RHS;
13920   if (Op1.getOpcode() == ISD::SHL)
13921     std::swap(Op0, Op1);
13922   if (Op0.getOpcode() == ISD::SHL) {
13923     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13924       if (And00C->getZExtValue() == 1) {
13925         // If we looked past a truncate, check that it's only truncating away
13926         // known zeros.
13927         unsigned BitWidth = Op0.getValueSizeInBits();
13928         unsigned AndBitWidth = And.getValueSizeInBits();
13929         if (BitWidth > AndBitWidth) {
13930           APInt Zeros, Ones;
13931           DAG.computeKnownBits(Op0, Zeros, Ones);
13932           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13933             return SDValue();
13934         }
13935         LHS = Op1;
13936         RHS = Op0.getOperand(1);
13937       }
13938   } else if (Op1.getOpcode() == ISD::Constant) {
13939     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13940     uint64_t AndRHSVal = AndRHS->getZExtValue();
13941     SDValue AndLHS = Op0;
13942
13943     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13944       LHS = AndLHS.getOperand(0);
13945       RHS = AndLHS.getOperand(1);
13946     }
13947
13948     // Use BT if the immediate can't be encoded in a TEST instruction.
13949     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13950       LHS = AndLHS;
13951       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13952     }
13953   }
13954
13955   if (LHS.getNode()) {
13956     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13957     // instruction.  Since the shift amount is in-range-or-undefined, we know
13958     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13959     // the encoding for the i16 version is larger than the i32 version.
13960     // Also promote i16 to i32 for performance / code size reason.
13961     if (LHS.getValueType() == MVT::i8 ||
13962         LHS.getValueType() == MVT::i16)
13963       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13964
13965     // If the operand types disagree, extend the shift amount to match.  Since
13966     // BT ignores high bits (like shifts) we can use anyextend.
13967     if (LHS.getValueType() != RHS.getValueType())
13968       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13969
13970     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13971     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13972     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13973                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13974   }
13975
13976   return SDValue();
13977 }
13978
13979 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13980 /// mask CMPs.
13981 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13982                               SDValue &Op1) {
13983   unsigned SSECC;
13984   bool Swap = false;
13985
13986   // SSE Condition code mapping:
13987   //  0 - EQ
13988   //  1 - LT
13989   //  2 - LE
13990   //  3 - UNORD
13991   //  4 - NEQ
13992   //  5 - NLT
13993   //  6 - NLE
13994   //  7 - ORD
13995   switch (SetCCOpcode) {
13996   default: llvm_unreachable("Unexpected SETCC condition");
13997   case ISD::SETOEQ:
13998   case ISD::SETEQ:  SSECC = 0; break;
13999   case ISD::SETOGT:
14000   case ISD::SETGT:  Swap = true; // Fallthrough
14001   case ISD::SETLT:
14002   case ISD::SETOLT: SSECC = 1; break;
14003   case ISD::SETOGE:
14004   case ISD::SETGE:  Swap = true; // Fallthrough
14005   case ISD::SETLE:
14006   case ISD::SETOLE: SSECC = 2; break;
14007   case ISD::SETUO:  SSECC = 3; break;
14008   case ISD::SETUNE:
14009   case ISD::SETNE:  SSECC = 4; break;
14010   case ISD::SETULE: Swap = true; // Fallthrough
14011   case ISD::SETUGE: SSECC = 5; break;
14012   case ISD::SETULT: Swap = true; // Fallthrough
14013   case ISD::SETUGT: SSECC = 6; break;
14014   case ISD::SETO:   SSECC = 7; break;
14015   case ISD::SETUEQ:
14016   case ISD::SETONE: SSECC = 8; break;
14017   }
14018   if (Swap)
14019     std::swap(Op0, Op1);
14020
14021   return SSECC;
14022 }
14023
14024 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14025 // ones, and then concatenate the result back.
14026 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14027   MVT VT = Op.getSimpleValueType();
14028
14029   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14030          "Unsupported value type for operation");
14031
14032   unsigned NumElems = VT.getVectorNumElements();
14033   SDLoc dl(Op);
14034   SDValue CC = Op.getOperand(2);
14035
14036   // Extract the LHS vectors
14037   SDValue LHS = Op.getOperand(0);
14038   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14039   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14040
14041   // Extract the RHS vectors
14042   SDValue RHS = Op.getOperand(1);
14043   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14044   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14045
14046   // Issue the operation on the smaller types and concatenate the result back
14047   MVT EltVT = VT.getVectorElementType();
14048   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14049   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14050                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14051                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14052 }
14053
14054 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
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() == MVT::i1 &&
14062          "Unexpected type for boolean compare operation");
14063   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14064   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14065                                DAG.getConstant(-1, dl, VT));
14066   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14067                                DAG.getConstant(-1, dl, VT));
14068   switch (SetCCOpcode) {
14069   default: llvm_unreachable("Unexpected SETCC condition");
14070   case ISD::SETEQ:
14071     // (x == y) -> ~(x ^ y)
14072     return DAG.getNode(ISD::XOR, dl, VT,
14073                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14074                        DAG.getConstant(-1, dl, VT));
14075   case ISD::SETNE:
14076     // (x != y) -> (x ^ y)
14077     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14078   case ISD::SETUGT:
14079   case ISD::SETGT:
14080     // (x > y) -> (x & ~y)
14081     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14082   case ISD::SETULT:
14083   case ISD::SETLT:
14084     // (x < y) -> (~x & y)
14085     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14086   case ISD::SETULE:
14087   case ISD::SETLE:
14088     // (x <= y) -> (~x | y)
14089     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14090   case ISD::SETUGE:
14091   case ISD::SETGE:
14092     // (x >=y) -> (x | ~y)
14093     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14094   }
14095 }
14096
14097 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14098                                      const X86Subtarget *Subtarget) {
14099   SDValue Op0 = Op.getOperand(0);
14100   SDValue Op1 = Op.getOperand(1);
14101   SDValue CC = Op.getOperand(2);
14102   MVT VT = Op.getSimpleValueType();
14103   SDLoc dl(Op);
14104
14105   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14106          Op.getValueType().getScalarType() == MVT::i1 &&
14107          "Cannot set masked compare for this operation");
14108
14109   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14110   unsigned  Opc = 0;
14111   bool Unsigned = false;
14112   bool Swap = false;
14113   unsigned SSECC;
14114   switch (SetCCOpcode) {
14115   default: llvm_unreachable("Unexpected SETCC condition");
14116   case ISD::SETNE:  SSECC = 4; break;
14117   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14118   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14119   case ISD::SETLT:  Swap = true; //fall-through
14120   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14121   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14122   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14123   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14124   case ISD::SETULE: Unsigned = true; //fall-through
14125   case ISD::SETLE:  SSECC = 2; break;
14126   }
14127
14128   if (Swap)
14129     std::swap(Op0, Op1);
14130   if (Opc)
14131     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14132   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14133   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14134                      DAG.getConstant(SSECC, dl, MVT::i8));
14135 }
14136
14137 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14138 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14139 /// return an empty value.
14140 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14141 {
14142   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14143   if (!BV)
14144     return SDValue();
14145
14146   MVT VT = Op1.getSimpleValueType();
14147   MVT EVT = VT.getVectorElementType();
14148   unsigned n = VT.getVectorNumElements();
14149   SmallVector<SDValue, 8> ULTOp1;
14150
14151   for (unsigned i = 0; i < n; ++i) {
14152     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14153     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14154       return SDValue();
14155
14156     // Avoid underflow.
14157     APInt Val = Elt->getAPIntValue();
14158     if (Val == 0)
14159       return SDValue();
14160
14161     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14162   }
14163
14164   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14165 }
14166
14167 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14168                            SelectionDAG &DAG) {
14169   SDValue Op0 = Op.getOperand(0);
14170   SDValue Op1 = Op.getOperand(1);
14171   SDValue CC = Op.getOperand(2);
14172   MVT VT = Op.getSimpleValueType();
14173   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14174   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14175   SDLoc dl(Op);
14176
14177   if (isFP) {
14178 #ifndef NDEBUG
14179     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14180     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14181 #endif
14182
14183     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14184     unsigned Opc = X86ISD::CMPP;
14185     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14186       assert(VT.getVectorNumElements() <= 16);
14187       Opc = X86ISD::CMPM;
14188     }
14189     // In the two special cases we can't handle, emit two comparisons.
14190     if (SSECC == 8) {
14191       unsigned CC0, CC1;
14192       unsigned CombineOpc;
14193       if (SetCCOpcode == ISD::SETUEQ) {
14194         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14195       } else {
14196         assert(SetCCOpcode == ISD::SETONE);
14197         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14198       }
14199
14200       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14201                                  DAG.getConstant(CC0, dl, MVT::i8));
14202       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14203                                  DAG.getConstant(CC1, dl, MVT::i8));
14204       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14205     }
14206     // Handle all other FP comparisons here.
14207     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14208                        DAG.getConstant(SSECC, dl, MVT::i8));
14209   }
14210
14211   MVT VTOp0 = Op0.getSimpleValueType();
14212   assert(VTOp0 == Op1.getSimpleValueType() &&
14213          "Expected operands with same type!");
14214   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14215          "Invalid number of packed elements for source and destination!");
14216
14217   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14218     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14219     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14220     // legalizer firstly checks if the first operand in input to the setcc has
14221     // a legal type. If so, then it promotes the return type to that same type.
14222     // Otherwise, the return type is promoted to the 'next legal type' which,
14223     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14224     //
14225     // We reach this code only if the following two conditions are met:
14226     // 1. Both return type and operand type have been promoted to wider types
14227     //    by the type legalizer.
14228     // 2. The original operand type has been promoted to a 256-bit vector.
14229     //
14230     // Note that condition 2. only applies for AVX targets.
14231     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14232     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14233   }
14234
14235   // The non-AVX512 code below works under the assumption that source and
14236   // destination types are the same.
14237   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14238          "Value types for source and destination must be the same!");
14239
14240   // Break 256-bit integer vector compare into smaller ones.
14241   if (VT.is256BitVector() && !Subtarget->hasInt256())
14242     return Lower256IntVSETCC(Op, DAG);
14243
14244   EVT OpVT = Op1.getValueType();
14245   if (OpVT.getVectorElementType() == MVT::i1)
14246     return LowerBoolVSETCC_AVX512(Op, DAG);
14247
14248   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14249   if (Subtarget->hasAVX512()) {
14250     if (Op1.getValueType().is512BitVector() ||
14251         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14252         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14253       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14254
14255     // In AVX-512 architecture setcc returns mask with i1 elements,
14256     // But there is no compare instruction for i8 and i16 elements in KNL.
14257     // We are not talking about 512-bit operands in this case, these
14258     // types are illegal.
14259     if (MaskResult &&
14260         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14261          OpVT.getVectorElementType().getSizeInBits() >= 8))
14262       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14263                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14264   }
14265
14266   // Lower using XOP integer comparisons.
14267   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14268        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14269     // Translate compare code to XOP PCOM compare mode.
14270     unsigned CmpMode = 0;
14271     switch (SetCCOpcode) {
14272     default: llvm_unreachable("Unexpected SETCC condition");
14273     case ISD::SETULT:
14274     case ISD::SETLT: CmpMode = 0x00; break;
14275     case ISD::SETULE:
14276     case ISD::SETLE: CmpMode = 0x01; break;
14277     case ISD::SETUGT:
14278     case ISD::SETGT: CmpMode = 0x02; break;
14279     case ISD::SETUGE:
14280     case ISD::SETGE: CmpMode = 0x03; break;
14281     case ISD::SETEQ: CmpMode = 0x04; break;
14282     case ISD::SETNE: CmpMode = 0x05; break;
14283     }
14284
14285     // Are we comparing unsigned or signed integers?
14286     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14287       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14288
14289     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14290                        DAG.getConstant(CmpMode, dl, MVT::i8));
14291   }
14292
14293   // We are handling one of the integer comparisons here.  Since SSE only has
14294   // GT and EQ comparisons for integer, swapping operands and multiple
14295   // operations may be required for some comparisons.
14296   unsigned Opc;
14297   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14298   bool Subus = false;
14299
14300   switch (SetCCOpcode) {
14301   default: llvm_unreachable("Unexpected SETCC condition");
14302   case ISD::SETNE:  Invert = true;
14303   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14304   case ISD::SETLT:  Swap = true;
14305   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14306   case ISD::SETGE:  Swap = true;
14307   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14308                     Invert = true; break;
14309   case ISD::SETULT: Swap = true;
14310   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14311                     FlipSigns = true; break;
14312   case ISD::SETUGE: Swap = true;
14313   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14314                     FlipSigns = true; Invert = true; break;
14315   }
14316
14317   // Special case: Use min/max operations for SETULE/SETUGE
14318   MVT VET = VT.getVectorElementType();
14319   bool hasMinMax =
14320        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14321     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14322
14323   if (hasMinMax) {
14324     switch (SetCCOpcode) {
14325     default: break;
14326     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14327     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14328     }
14329
14330     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14331   }
14332
14333   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14334   if (!MinMax && hasSubus) {
14335     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14336     // Op0 u<= Op1:
14337     //   t = psubus Op0, Op1
14338     //   pcmpeq t, <0..0>
14339     switch (SetCCOpcode) {
14340     default: break;
14341     case ISD::SETULT: {
14342       // If the comparison is against a constant we can turn this into a
14343       // setule.  With psubus, setule does not require a swap.  This is
14344       // beneficial because the constant in the register is no longer
14345       // destructed as the destination so it can be hoisted out of a loop.
14346       // Only do this pre-AVX since vpcmp* is no longer destructive.
14347       if (Subtarget->hasAVX())
14348         break;
14349       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14350       if (ULEOp1.getNode()) {
14351         Op1 = ULEOp1;
14352         Subus = true; Invert = false; Swap = false;
14353       }
14354       break;
14355     }
14356     // Psubus is better than flip-sign because it requires no inversion.
14357     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14358     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14359     }
14360
14361     if (Subus) {
14362       Opc = X86ISD::SUBUS;
14363       FlipSigns = false;
14364     }
14365   }
14366
14367   if (Swap)
14368     std::swap(Op0, Op1);
14369
14370   // Check that the operation in question is available (most are plain SSE2,
14371   // but PCMPGTQ and PCMPEQQ have different requirements).
14372   if (VT == MVT::v2i64) {
14373     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14374       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14375
14376       // First cast everything to the right type.
14377       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14378       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14379
14380       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14381       // bits of the inputs before performing those operations. The lower
14382       // compare is always unsigned.
14383       SDValue SB;
14384       if (FlipSigns) {
14385         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14386       } else {
14387         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14388         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14389         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14390                          Sign, Zero, Sign, Zero);
14391       }
14392       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14393       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14394
14395       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14396       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14397       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14398
14399       // Create masks for only the low parts/high parts of the 64 bit integers.
14400       static const int MaskHi[] = { 1, 1, 3, 3 };
14401       static const int MaskLo[] = { 0, 0, 2, 2 };
14402       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14403       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14404       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14405
14406       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14407       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14408
14409       if (Invert)
14410         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14411
14412       return DAG.getBitcast(VT, Result);
14413     }
14414
14415     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14416       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14417       // pcmpeqd + pshufd + pand.
14418       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14419
14420       // First cast everything to the right type.
14421       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14422       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14423
14424       // Do the compare.
14425       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14426
14427       // Make sure the lower and upper halves are both all-ones.
14428       static const int Mask[] = { 1, 0, 3, 2 };
14429       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14430       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14431
14432       if (Invert)
14433         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14434
14435       return DAG.getBitcast(VT, Result);
14436     }
14437   }
14438
14439   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14440   // bits of the inputs before performing those operations.
14441   if (FlipSigns) {
14442     EVT EltVT = VT.getVectorElementType();
14443     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14444                                  VT);
14445     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14446     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14447   }
14448
14449   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14450
14451   // If the logical-not of the result is required, perform that now.
14452   if (Invert)
14453     Result = DAG.getNOT(dl, Result, VT);
14454
14455   if (MinMax)
14456     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14457
14458   if (Subus)
14459     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14460                          getZeroVector(VT, Subtarget, DAG, dl));
14461
14462   return Result;
14463 }
14464
14465 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14466
14467   MVT VT = Op.getSimpleValueType();
14468
14469   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14470
14471   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14472          && "SetCC type must be 8-bit or 1-bit integer");
14473   SDValue Op0 = Op.getOperand(0);
14474   SDValue Op1 = Op.getOperand(1);
14475   SDLoc dl(Op);
14476   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14477
14478   // Optimize to BT if possible.
14479   // Lower (X & (1 << N)) == 0 to BT(X, N).
14480   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14481   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14482   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14483       Op1.getOpcode() == ISD::Constant &&
14484       cast<ConstantSDNode>(Op1)->isNullValue() &&
14485       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14486     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14487     if (NewSetCC.getNode()) {
14488       if (VT == MVT::i1)
14489         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14490       return NewSetCC;
14491     }
14492   }
14493
14494   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14495   // these.
14496   if (Op1.getOpcode() == ISD::Constant &&
14497       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14498        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14499       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14500
14501     // If the input is a setcc, then reuse the input setcc or use a new one with
14502     // the inverted condition.
14503     if (Op0.getOpcode() == X86ISD::SETCC) {
14504       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14505       bool Invert = (CC == ISD::SETNE) ^
14506         cast<ConstantSDNode>(Op1)->isNullValue();
14507       if (!Invert)
14508         return Op0;
14509
14510       CCode = X86::GetOppositeBranchCondition(CCode);
14511       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14512                                   DAG.getConstant(CCode, dl, MVT::i8),
14513                                   Op0.getOperand(1));
14514       if (VT == MVT::i1)
14515         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14516       return SetCC;
14517     }
14518   }
14519   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14520       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14521       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14522
14523     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14524     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14525   }
14526
14527   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14528   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14529   if (X86CC == X86::COND_INVALID)
14530     return SDValue();
14531
14532   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14533   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14534   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14535                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14536   if (VT == MVT::i1)
14537     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14538   return SetCC;
14539 }
14540
14541 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14542 static bool isX86LogicalCmp(SDValue Op) {
14543   unsigned Opc = Op.getNode()->getOpcode();
14544   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14545       Opc == X86ISD::SAHF)
14546     return true;
14547   if (Op.getResNo() == 1 &&
14548       (Opc == X86ISD::ADD ||
14549        Opc == X86ISD::SUB ||
14550        Opc == X86ISD::ADC ||
14551        Opc == X86ISD::SBB ||
14552        Opc == X86ISD::SMUL ||
14553        Opc == X86ISD::UMUL ||
14554        Opc == X86ISD::INC ||
14555        Opc == X86ISD::DEC ||
14556        Opc == X86ISD::OR ||
14557        Opc == X86ISD::XOR ||
14558        Opc == X86ISD::AND))
14559     return true;
14560
14561   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14562     return true;
14563
14564   return false;
14565 }
14566
14567 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14568   if (V.getOpcode() != ISD::TRUNCATE)
14569     return false;
14570
14571   SDValue VOp0 = V.getOperand(0);
14572   unsigned InBits = VOp0.getValueSizeInBits();
14573   unsigned Bits = V.getValueSizeInBits();
14574   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14575 }
14576
14577 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14578   bool addTest = true;
14579   SDValue Cond  = Op.getOperand(0);
14580   SDValue Op1 = Op.getOperand(1);
14581   SDValue Op2 = Op.getOperand(2);
14582   SDLoc DL(Op);
14583   EVT VT = Op1.getValueType();
14584   SDValue CC;
14585
14586   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14587   // are available or VBLENDV if AVX is available.
14588   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14589   if (Cond.getOpcode() == ISD::SETCC &&
14590       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14591        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14592       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14593     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14594     int SSECC = translateX86FSETCC(
14595         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14596
14597     if (SSECC != 8) {
14598       if (Subtarget->hasAVX512()) {
14599         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14600                                   DAG.getConstant(SSECC, DL, MVT::i8));
14601         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14602       }
14603
14604       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14605                                 DAG.getConstant(SSECC, DL, MVT::i8));
14606
14607       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14608       // of 3 logic instructions for size savings and potentially speed.
14609       // Unfortunately, there is no scalar form of VBLENDV.
14610
14611       // If either operand is a constant, don't try this. We can expect to
14612       // optimize away at least one of the logic instructions later in that
14613       // case, so that sequence would be faster than a variable blend.
14614
14615       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14616       // uses XMM0 as the selection register. That may need just as many
14617       // instructions as the AND/ANDN/OR sequence due to register moves, so
14618       // don't bother.
14619
14620       if (Subtarget->hasAVX() &&
14621           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14622
14623         // Convert to vectors, do a VSELECT, and convert back to scalar.
14624         // All of the conversions should be optimized away.
14625
14626         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14627         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14628         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14629         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14630
14631         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14632         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14633
14634         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14635
14636         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14637                            VSel, DAG.getIntPtrConstant(0, DL));
14638       }
14639       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14640       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14641       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14642     }
14643   }
14644
14645   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14646     SDValue Op1Scalar;
14647     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14648       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14649     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14650       Op1Scalar = Op1.getOperand(0);
14651     SDValue Op2Scalar;
14652     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14653       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14654     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14655       Op2Scalar = Op2.getOperand(0);
14656     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14657       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14658                                       Op1Scalar.getValueType(),
14659                                       Cond, Op1Scalar, Op2Scalar);
14660       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14661         return DAG.getBitcast(VT, newSelect);
14662       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14663       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14664                          DAG.getIntPtrConstant(0, DL));
14665     }
14666   }
14667
14668   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14669     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14670     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14671                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14672     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14673                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14674     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14675                                     Cond, Op1, Op2);
14676     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14677   }
14678
14679   if (Cond.getOpcode() == ISD::SETCC) {
14680     SDValue NewCond = LowerSETCC(Cond, DAG);
14681     if (NewCond.getNode())
14682       Cond = NewCond;
14683   }
14684
14685   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14686   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14687   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14688   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14689   if (Cond.getOpcode() == X86ISD::SETCC &&
14690       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14691       isZero(Cond.getOperand(1).getOperand(1))) {
14692     SDValue Cmp = Cond.getOperand(1);
14693
14694     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14695
14696     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14697         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14698       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14699
14700       SDValue CmpOp0 = Cmp.getOperand(0);
14701       // Apply further optimizations for special cases
14702       // (select (x != 0), -1, 0) -> neg & sbb
14703       // (select (x == 0), 0, -1) -> neg & sbb
14704       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14705         if (YC->isNullValue() &&
14706             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14707           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14708           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14709                                     DAG.getConstant(0, DL,
14710                                                     CmpOp0.getValueType()),
14711                                     CmpOp0);
14712           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14713                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14714                                     SDValue(Neg.getNode(), 1));
14715           return Res;
14716         }
14717
14718       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14719                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14720       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14721
14722       SDValue Res =   // Res = 0 or -1.
14723         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14724                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14725
14726       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14727         Res = DAG.getNOT(DL, Res, Res.getValueType());
14728
14729       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14730       if (!N2C || !N2C->isNullValue())
14731         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14732       return Res;
14733     }
14734   }
14735
14736   // Look past (and (setcc_carry (cmp ...)), 1).
14737   if (Cond.getOpcode() == ISD::AND &&
14738       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14739     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14740     if (C && C->getAPIntValue() == 1)
14741       Cond = Cond.getOperand(0);
14742   }
14743
14744   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14745   // setting operand in place of the X86ISD::SETCC.
14746   unsigned CondOpcode = Cond.getOpcode();
14747   if (CondOpcode == X86ISD::SETCC ||
14748       CondOpcode == X86ISD::SETCC_CARRY) {
14749     CC = Cond.getOperand(0);
14750
14751     SDValue Cmp = Cond.getOperand(1);
14752     unsigned Opc = Cmp.getOpcode();
14753     MVT VT = Op.getSimpleValueType();
14754
14755     bool IllegalFPCMov = false;
14756     if (VT.isFloatingPoint() && !VT.isVector() &&
14757         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14758       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14759
14760     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14761         Opc == X86ISD::BT) { // FIXME
14762       Cond = Cmp;
14763       addTest = false;
14764     }
14765   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14766              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14767              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14768               Cond.getOperand(0).getValueType() != MVT::i8)) {
14769     SDValue LHS = Cond.getOperand(0);
14770     SDValue RHS = Cond.getOperand(1);
14771     unsigned X86Opcode;
14772     unsigned X86Cond;
14773     SDVTList VTs;
14774     switch (CondOpcode) {
14775     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14776     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14777     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14778     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14779     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14780     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14781     default: llvm_unreachable("unexpected overflowing operator");
14782     }
14783     if (CondOpcode == ISD::UMULO)
14784       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14785                           MVT::i32);
14786     else
14787       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14788
14789     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14790
14791     if (CondOpcode == ISD::UMULO)
14792       Cond = X86Op.getValue(2);
14793     else
14794       Cond = X86Op.getValue(1);
14795
14796     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14797     addTest = false;
14798   }
14799
14800   if (addTest) {
14801     // Look past the truncate if the high bits are known zero.
14802     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14803       Cond = Cond.getOperand(0);
14804
14805     // We know the result of AND is compared against zero. Try to match
14806     // it to BT.
14807     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14808       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14809       if (NewSetCC.getNode()) {
14810         CC = NewSetCC.getOperand(0);
14811         Cond = NewSetCC.getOperand(1);
14812         addTest = false;
14813       }
14814     }
14815   }
14816
14817   if (addTest) {
14818     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14819     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14820   }
14821
14822   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14823   // a <  b ?  0 : -1 -> RES = setcc_carry
14824   // a >= b ? -1 :  0 -> RES = setcc_carry
14825   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14826   if (Cond.getOpcode() == X86ISD::SUB) {
14827     Cond = ConvertCmpIfNecessary(Cond, DAG);
14828     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14829
14830     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14831         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14832       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14833                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14834                                 Cond);
14835       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14836         return DAG.getNOT(DL, Res, Res.getValueType());
14837       return Res;
14838     }
14839   }
14840
14841   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14842   // widen the cmov and push the truncate through. This avoids introducing a new
14843   // branch during isel and doesn't add any extensions.
14844   if (Op.getValueType() == MVT::i8 &&
14845       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14846     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14847     if (T1.getValueType() == T2.getValueType() &&
14848         // Blacklist CopyFromReg to avoid partial register stalls.
14849         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14850       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14851       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14852       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14853     }
14854   }
14855
14856   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14857   // condition is true.
14858   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14859   SDValue Ops[] = { Op2, Op1, CC, Cond };
14860   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14861 }
14862
14863 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14864                                        const X86Subtarget *Subtarget,
14865                                        SelectionDAG &DAG) {
14866   MVT VT = Op->getSimpleValueType(0);
14867   SDValue In = Op->getOperand(0);
14868   MVT InVT = In.getSimpleValueType();
14869   MVT VTElt = VT.getVectorElementType();
14870   MVT InVTElt = InVT.getVectorElementType();
14871   SDLoc dl(Op);
14872
14873   // SKX processor
14874   if ((InVTElt == MVT::i1) &&
14875       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14876         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14877
14878        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14879         VTElt.getSizeInBits() <= 16)) ||
14880
14881        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14882         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14883
14884        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14885         VTElt.getSizeInBits() >= 32))))
14886     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14887
14888   unsigned int NumElts = VT.getVectorNumElements();
14889
14890   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14891     return SDValue();
14892
14893   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14894     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14895       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14896     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14897   }
14898
14899   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14900   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14901   SDValue NegOne =
14902    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14903                    ExtVT);
14904   SDValue Zero =
14905    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14906
14907   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14908   if (VT.is512BitVector())
14909     return V;
14910   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14911 }
14912
14913 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14914                                              const X86Subtarget *Subtarget,
14915                                              SelectionDAG &DAG) {
14916   SDValue In = Op->getOperand(0);
14917   MVT VT = Op->getSimpleValueType(0);
14918   MVT InVT = In.getSimpleValueType();
14919   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14920
14921   MVT InSVT = InVT.getScalarType();
14922   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14923
14924   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14925     return SDValue();
14926   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14927     return SDValue();
14928
14929   SDLoc dl(Op);
14930
14931   // SSE41 targets can use the pmovsx* instructions directly.
14932   if (Subtarget->hasSSE41())
14933     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14934
14935   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14936   SDValue Curr = In;
14937   MVT CurrVT = InVT;
14938
14939   // As SRAI is only available on i16/i32 types, we expand only up to i32
14940   // and handle i64 separately.
14941   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14942     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14943     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14944     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14945     Curr = DAG.getBitcast(CurrVT, Curr);
14946   }
14947
14948   SDValue SignExt = Curr;
14949   if (CurrVT != InVT) {
14950     unsigned SignExtShift =
14951         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14952     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14953                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14954   }
14955
14956   if (CurrVT == VT)
14957     return SignExt;
14958
14959   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14960     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14961                                DAG.getConstant(31, dl, MVT::i8));
14962     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14963     return DAG.getBitcast(VT, Ext);
14964   }
14965
14966   return SDValue();
14967 }
14968
14969 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14970                                 SelectionDAG &DAG) {
14971   MVT VT = Op->getSimpleValueType(0);
14972   SDValue In = Op->getOperand(0);
14973   MVT InVT = In.getSimpleValueType();
14974   SDLoc dl(Op);
14975
14976   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14977     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14978
14979   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14980       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14981       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14982     return SDValue();
14983
14984   if (Subtarget->hasInt256())
14985     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14986
14987   // Optimize vectors in AVX mode
14988   // Sign extend  v8i16 to v8i32 and
14989   //              v4i32 to v4i64
14990   //
14991   // Divide input vector into two parts
14992   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14993   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14994   // concat the vectors to original VT
14995
14996   unsigned NumElems = InVT.getVectorNumElements();
14997   SDValue Undef = DAG.getUNDEF(InVT);
14998
14999   SmallVector<int,8> ShufMask1(NumElems, -1);
15000   for (unsigned i = 0; i != NumElems/2; ++i)
15001     ShufMask1[i] = i;
15002
15003   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15004
15005   SmallVector<int,8> ShufMask2(NumElems, -1);
15006   for (unsigned i = 0; i != NumElems/2; ++i)
15007     ShufMask2[i] = i + NumElems/2;
15008
15009   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15010
15011   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
15012                                 VT.getVectorNumElements()/2);
15013
15014   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15015   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15016
15017   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15018 }
15019
15020 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15021 // may emit an illegal shuffle but the expansion is still better than scalar
15022 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15023 // we'll emit a shuffle and a arithmetic shift.
15024 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15025 // TODO: It is possible to support ZExt by zeroing the undef values during
15026 // the shuffle phase or after the shuffle.
15027 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15028                                  SelectionDAG &DAG) {
15029   MVT RegVT = Op.getSimpleValueType();
15030   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15031   assert(RegVT.isInteger() &&
15032          "We only custom lower integer vector sext loads.");
15033
15034   // Nothing useful we can do without SSE2 shuffles.
15035   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15036
15037   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15038   SDLoc dl(Ld);
15039   EVT MemVT = Ld->getMemoryVT();
15040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15041   unsigned RegSz = RegVT.getSizeInBits();
15042
15043   ISD::LoadExtType Ext = Ld->getExtensionType();
15044
15045   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15046          && "Only anyext and sext are currently implemented.");
15047   assert(MemVT != RegVT && "Cannot extend to the same type");
15048   assert(MemVT.isVector() && "Must load a vector from memory");
15049
15050   unsigned NumElems = RegVT.getVectorNumElements();
15051   unsigned MemSz = MemVT.getSizeInBits();
15052   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15053
15054   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15055     // The only way in which we have a legal 256-bit vector result but not the
15056     // integer 256-bit operations needed to directly lower a sextload is if we
15057     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15058     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15059     // correctly legalized. We do this late to allow the canonical form of
15060     // sextload to persist throughout the rest of the DAG combiner -- it wants
15061     // to fold together any extensions it can, and so will fuse a sign_extend
15062     // of an sextload into a sextload targeting a wider value.
15063     SDValue Load;
15064     if (MemSz == 128) {
15065       // Just switch this to a normal load.
15066       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15067                                        "it must be a legal 128-bit vector "
15068                                        "type!");
15069       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15070                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15071                   Ld->isInvariant(), Ld->getAlignment());
15072     } else {
15073       assert(MemSz < 128 &&
15074              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15075       // Do an sext load to a 128-bit vector type. We want to use the same
15076       // number of elements, but elements half as wide. This will end up being
15077       // recursively lowered by this routine, but will succeed as we definitely
15078       // have all the necessary features if we're using AVX1.
15079       EVT HalfEltVT =
15080           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15081       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15082       Load =
15083           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15084                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15085                          Ld->isNonTemporal(), Ld->isInvariant(),
15086                          Ld->getAlignment());
15087     }
15088
15089     // Replace chain users with the new chain.
15090     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15091     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15092
15093     // Finally, do a normal sign-extend to the desired register.
15094     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15095   }
15096
15097   // All sizes must be a power of two.
15098   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15099          "Non-power-of-two elements are not custom lowered!");
15100
15101   // Attempt to load the original value using scalar loads.
15102   // Find the largest scalar type that divides the total loaded size.
15103   MVT SclrLoadTy = MVT::i8;
15104   for (MVT Tp : MVT::integer_valuetypes()) {
15105     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15106       SclrLoadTy = Tp;
15107     }
15108   }
15109
15110   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15111   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15112       (64 <= MemSz))
15113     SclrLoadTy = MVT::f64;
15114
15115   // Calculate the number of scalar loads that we need to perform
15116   // in order to load our vector from memory.
15117   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15118
15119   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15120          "Can only lower sext loads with a single scalar load!");
15121
15122   unsigned loadRegZize = RegSz;
15123   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15124     loadRegZize = 128;
15125
15126   // Represent our vector as a sequence of elements which are the
15127   // largest scalar that we can load.
15128   EVT LoadUnitVecVT = EVT::getVectorVT(
15129       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15130
15131   // Represent the data using the same element type that is stored in
15132   // memory. In practice, we ''widen'' MemVT.
15133   EVT WideVecVT =
15134       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15135                        loadRegZize / MemVT.getScalarType().getSizeInBits());
15136
15137   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15138          "Invalid vector type");
15139
15140   // We can't shuffle using an illegal type.
15141   assert(TLI.isTypeLegal(WideVecVT) &&
15142          "We only lower types that form legal widened vector types");
15143
15144   SmallVector<SDValue, 8> Chains;
15145   SDValue Ptr = Ld->getBasePtr();
15146   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15147                                       TLI.getPointerTy(DAG.getDataLayout()));
15148   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15149
15150   for (unsigned i = 0; i < NumLoads; ++i) {
15151     // Perform a single load.
15152     SDValue ScalarLoad =
15153         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15154                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15155                     Ld->getAlignment());
15156     Chains.push_back(ScalarLoad.getValue(1));
15157     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15158     // another round of DAGCombining.
15159     if (i == 0)
15160       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15161     else
15162       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15163                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15164
15165     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15166   }
15167
15168   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15169
15170   // Bitcast the loaded value to a vector of the original element type, in
15171   // the size of the target vector type.
15172   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15173   unsigned SizeRatio = RegSz / MemSz;
15174
15175   if (Ext == ISD::SEXTLOAD) {
15176     // If we have SSE4.1, we can directly emit a VSEXT node.
15177     if (Subtarget->hasSSE41()) {
15178       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15179       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15180       return Sext;
15181     }
15182
15183     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15184     // lanes.
15185     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15186            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15187
15188     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15189     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15190     return Shuff;
15191   }
15192
15193   // Redistribute the loaded elements into the different locations.
15194   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15195   for (unsigned i = 0; i != NumElems; ++i)
15196     ShuffleVec[i * SizeRatio] = i;
15197
15198   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15199                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15200
15201   // Bitcast to the requested type.
15202   Shuff = DAG.getBitcast(RegVT, Shuff);
15203   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15204   return Shuff;
15205 }
15206
15207 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15208 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15209 // from the AND / OR.
15210 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15211   Opc = Op.getOpcode();
15212   if (Opc != ISD::OR && Opc != ISD::AND)
15213     return false;
15214   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15215           Op.getOperand(0).hasOneUse() &&
15216           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15217           Op.getOperand(1).hasOneUse());
15218 }
15219
15220 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15221 // 1 and that the SETCC node has a single use.
15222 static bool isXor1OfSetCC(SDValue Op) {
15223   if (Op.getOpcode() != ISD::XOR)
15224     return false;
15225   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15226   if (N1C && N1C->getAPIntValue() == 1) {
15227     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15228       Op.getOperand(0).hasOneUse();
15229   }
15230   return false;
15231 }
15232
15233 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15234   bool addTest = true;
15235   SDValue Chain = Op.getOperand(0);
15236   SDValue Cond  = Op.getOperand(1);
15237   SDValue Dest  = Op.getOperand(2);
15238   SDLoc dl(Op);
15239   SDValue CC;
15240   bool Inverted = false;
15241
15242   if (Cond.getOpcode() == ISD::SETCC) {
15243     // Check for setcc([su]{add,sub,mul}o == 0).
15244     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15245         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15246         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15247         Cond.getOperand(0).getResNo() == 1 &&
15248         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15249          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15250          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15251          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15252          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15253          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15254       Inverted = true;
15255       Cond = Cond.getOperand(0);
15256     } else {
15257       SDValue NewCond = LowerSETCC(Cond, DAG);
15258       if (NewCond.getNode())
15259         Cond = NewCond;
15260     }
15261   }
15262 #if 0
15263   // FIXME: LowerXALUO doesn't handle these!!
15264   else if (Cond.getOpcode() == X86ISD::ADD  ||
15265            Cond.getOpcode() == X86ISD::SUB  ||
15266            Cond.getOpcode() == X86ISD::SMUL ||
15267            Cond.getOpcode() == X86ISD::UMUL)
15268     Cond = LowerXALUO(Cond, DAG);
15269 #endif
15270
15271   // Look pass (and (setcc_carry (cmp ...)), 1).
15272   if (Cond.getOpcode() == ISD::AND &&
15273       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15274     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15275     if (C && C->getAPIntValue() == 1)
15276       Cond = Cond.getOperand(0);
15277   }
15278
15279   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15280   // setting operand in place of the X86ISD::SETCC.
15281   unsigned CondOpcode = Cond.getOpcode();
15282   if (CondOpcode == X86ISD::SETCC ||
15283       CondOpcode == X86ISD::SETCC_CARRY) {
15284     CC = Cond.getOperand(0);
15285
15286     SDValue Cmp = Cond.getOperand(1);
15287     unsigned Opc = Cmp.getOpcode();
15288     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15289     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15290       Cond = Cmp;
15291       addTest = false;
15292     } else {
15293       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15294       default: break;
15295       case X86::COND_O:
15296       case X86::COND_B:
15297         // These can only come from an arithmetic instruction with overflow,
15298         // e.g. SADDO, UADDO.
15299         Cond = Cond.getNode()->getOperand(1);
15300         addTest = false;
15301         break;
15302       }
15303     }
15304   }
15305   CondOpcode = Cond.getOpcode();
15306   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15307       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15308       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15309        Cond.getOperand(0).getValueType() != MVT::i8)) {
15310     SDValue LHS = Cond.getOperand(0);
15311     SDValue RHS = Cond.getOperand(1);
15312     unsigned X86Opcode;
15313     unsigned X86Cond;
15314     SDVTList VTs;
15315     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15316     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15317     // X86ISD::INC).
15318     switch (CondOpcode) {
15319     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15320     case ISD::SADDO:
15321       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15322         if (C->isOne()) {
15323           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15324           break;
15325         }
15326       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15327     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15328     case ISD::SSUBO:
15329       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15330         if (C->isOne()) {
15331           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15332           break;
15333         }
15334       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15335     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15336     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15337     default: llvm_unreachable("unexpected overflowing operator");
15338     }
15339     if (Inverted)
15340       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15341     if (CondOpcode == ISD::UMULO)
15342       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15343                           MVT::i32);
15344     else
15345       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15346
15347     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15348
15349     if (CondOpcode == ISD::UMULO)
15350       Cond = X86Op.getValue(2);
15351     else
15352       Cond = X86Op.getValue(1);
15353
15354     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15355     addTest = false;
15356   } else {
15357     unsigned CondOpc;
15358     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15359       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15360       if (CondOpc == ISD::OR) {
15361         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15362         // two branches instead of an explicit OR instruction with a
15363         // separate test.
15364         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15365             isX86LogicalCmp(Cmp)) {
15366           CC = Cond.getOperand(0).getOperand(0);
15367           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15368                               Chain, Dest, CC, Cmp);
15369           CC = Cond.getOperand(1).getOperand(0);
15370           Cond = Cmp;
15371           addTest = false;
15372         }
15373       } else { // ISD::AND
15374         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15375         // two branches instead of an explicit AND instruction with a
15376         // separate test. However, we only do this if this block doesn't
15377         // have a fall-through edge, because this requires an explicit
15378         // jmp when the condition is false.
15379         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15380             isX86LogicalCmp(Cmp) &&
15381             Op.getNode()->hasOneUse()) {
15382           X86::CondCode CCode =
15383             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15384           CCode = X86::GetOppositeBranchCondition(CCode);
15385           CC = DAG.getConstant(CCode, dl, MVT::i8);
15386           SDNode *User = *Op.getNode()->use_begin();
15387           // Look for an unconditional branch following this conditional branch.
15388           // We need this because we need to reverse the successors in order
15389           // to implement FCMP_OEQ.
15390           if (User->getOpcode() == ISD::BR) {
15391             SDValue FalseBB = User->getOperand(1);
15392             SDNode *NewBR =
15393               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15394             assert(NewBR == User);
15395             (void)NewBR;
15396             Dest = FalseBB;
15397
15398             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15399                                 Chain, Dest, CC, Cmp);
15400             X86::CondCode CCode =
15401               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15402             CCode = X86::GetOppositeBranchCondition(CCode);
15403             CC = DAG.getConstant(CCode, dl, MVT::i8);
15404             Cond = Cmp;
15405             addTest = false;
15406           }
15407         }
15408       }
15409     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15410       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15411       // It should be transformed during dag combiner except when the condition
15412       // is set by a arithmetics with overflow node.
15413       X86::CondCode CCode =
15414         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15415       CCode = X86::GetOppositeBranchCondition(CCode);
15416       CC = DAG.getConstant(CCode, dl, MVT::i8);
15417       Cond = Cond.getOperand(0).getOperand(1);
15418       addTest = false;
15419     } else if (Cond.getOpcode() == ISD::SETCC &&
15420                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15421       // For FCMP_OEQ, we can emit
15422       // two branches instead of an explicit AND instruction with a
15423       // separate test. However, we only do this if this block doesn't
15424       // have a fall-through edge, because this requires an explicit
15425       // jmp when the condition is false.
15426       if (Op.getNode()->hasOneUse()) {
15427         SDNode *User = *Op.getNode()->use_begin();
15428         // Look for an unconditional branch following this conditional branch.
15429         // We need this because we need to reverse the successors in order
15430         // to implement FCMP_OEQ.
15431         if (User->getOpcode() == ISD::BR) {
15432           SDValue FalseBB = User->getOperand(1);
15433           SDNode *NewBR =
15434             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15435           assert(NewBR == User);
15436           (void)NewBR;
15437           Dest = FalseBB;
15438
15439           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15440                                     Cond.getOperand(0), Cond.getOperand(1));
15441           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15442           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15443           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15444                               Chain, Dest, CC, Cmp);
15445           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15446           Cond = Cmp;
15447           addTest = false;
15448         }
15449       }
15450     } else if (Cond.getOpcode() == ISD::SETCC &&
15451                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15452       // For FCMP_UNE, we can emit
15453       // two branches instead of an explicit AND instruction with a
15454       // separate test. However, we only do this if this block doesn't
15455       // have a fall-through edge, because this requires an explicit
15456       // jmp when the condition is false.
15457       if (Op.getNode()->hasOneUse()) {
15458         SDNode *User = *Op.getNode()->use_begin();
15459         // Look for an unconditional branch following this conditional branch.
15460         // We need this because we need to reverse the successors in order
15461         // to implement FCMP_UNE.
15462         if (User->getOpcode() == ISD::BR) {
15463           SDValue FalseBB = User->getOperand(1);
15464           SDNode *NewBR =
15465             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15466           assert(NewBR == User);
15467           (void)NewBR;
15468
15469           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15470                                     Cond.getOperand(0), Cond.getOperand(1));
15471           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15472           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15473           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15474                               Chain, Dest, CC, Cmp);
15475           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15476           Cond = Cmp;
15477           addTest = false;
15478           Dest = FalseBB;
15479         }
15480       }
15481     }
15482   }
15483
15484   if (addTest) {
15485     // Look pass the truncate if the high bits are known zero.
15486     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15487         Cond = Cond.getOperand(0);
15488
15489     // We know the result of AND is compared against zero. Try to match
15490     // it to BT.
15491     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15492       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15493       if (NewSetCC.getNode()) {
15494         CC = NewSetCC.getOperand(0);
15495         Cond = NewSetCC.getOperand(1);
15496         addTest = false;
15497       }
15498     }
15499   }
15500
15501   if (addTest) {
15502     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15503     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15504     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15505   }
15506   Cond = ConvertCmpIfNecessary(Cond, DAG);
15507   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15508                      Chain, Dest, CC, Cond);
15509 }
15510
15511 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15512 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15513 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15514 // that the guard pages used by the OS virtual memory manager are allocated in
15515 // correct sequence.
15516 SDValue
15517 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15518                                            SelectionDAG &DAG) const {
15519   MachineFunction &MF = DAG.getMachineFunction();
15520   bool SplitStack = MF.shouldSplitStack();
15521   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15522                SplitStack;
15523   SDLoc dl(Op);
15524
15525   if (!Lower) {
15526     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15527     SDNode* Node = Op.getNode();
15528
15529     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15530     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15531         " not tell us which reg is the stack pointer!");
15532     EVT VT = Node->getValueType(0);
15533     SDValue Tmp1 = SDValue(Node, 0);
15534     SDValue Tmp2 = SDValue(Node, 1);
15535     SDValue Tmp3 = Node->getOperand(2);
15536     SDValue Chain = Tmp1.getOperand(0);
15537
15538     // Chain the dynamic stack allocation so that it doesn't modify the stack
15539     // pointer when other instructions are using the stack.
15540     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15541         SDLoc(Node));
15542
15543     SDValue Size = Tmp2.getOperand(1);
15544     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15545     Chain = SP.getValue(1);
15546     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15547     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15548     unsigned StackAlign = TFI.getStackAlignment();
15549     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15550     if (Align > StackAlign)
15551       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15552           DAG.getConstant(-(uint64_t)Align, dl, VT));
15553     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15554
15555     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15556         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15557         SDLoc(Node));
15558
15559     SDValue Ops[2] = { Tmp1, Tmp2 };
15560     return DAG.getMergeValues(Ops, dl);
15561   }
15562
15563   // Get the inputs.
15564   SDValue Chain = Op.getOperand(0);
15565   SDValue Size  = Op.getOperand(1);
15566   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15567   EVT VT = Op.getNode()->getValueType(0);
15568
15569   bool Is64Bit = Subtarget->is64Bit();
15570   MVT SPTy = getPointerTy(DAG.getDataLayout());
15571
15572   if (SplitStack) {
15573     MachineRegisterInfo &MRI = MF.getRegInfo();
15574
15575     if (Is64Bit) {
15576       // The 64 bit implementation of segmented stacks needs to clobber both r10
15577       // r11. This makes it impossible to use it along with nested parameters.
15578       const Function *F = MF.getFunction();
15579
15580       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15581            I != E; ++I)
15582         if (I->hasNestAttr())
15583           report_fatal_error("Cannot use segmented stacks with functions that "
15584                              "have nested arguments.");
15585     }
15586
15587     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15588     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15589     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15590     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15591                                 DAG.getRegister(Vreg, SPTy));
15592     SDValue Ops1[2] = { Value, Chain };
15593     return DAG.getMergeValues(Ops1, dl);
15594   } else {
15595     SDValue Flag;
15596     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15597
15598     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15599     Flag = Chain.getValue(1);
15600     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15601
15602     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15603
15604     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15605     unsigned SPReg = RegInfo->getStackRegister();
15606     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15607     Chain = SP.getValue(1);
15608
15609     if (Align) {
15610       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15611                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15612       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15613     }
15614
15615     SDValue Ops1[2] = { SP, Chain };
15616     return DAG.getMergeValues(Ops1, dl);
15617   }
15618 }
15619
15620 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15621   MachineFunction &MF = DAG.getMachineFunction();
15622   auto PtrVT = getPointerTy(MF.getDataLayout());
15623   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15624
15625   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15626   SDLoc DL(Op);
15627
15628   if (!Subtarget->is64Bit() ||
15629       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15630     // vastart just stores the address of the VarArgsFrameIndex slot into the
15631     // memory location argument.
15632     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15633     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15634                         MachinePointerInfo(SV), false, false, 0);
15635   }
15636
15637   // __va_list_tag:
15638   //   gp_offset         (0 - 6 * 8)
15639   //   fp_offset         (48 - 48 + 8 * 16)
15640   //   overflow_arg_area (point to parameters coming in memory).
15641   //   reg_save_area
15642   SmallVector<SDValue, 8> MemOps;
15643   SDValue FIN = Op.getOperand(1);
15644   // Store gp_offset
15645   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15646                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15647                                                DL, MVT::i32),
15648                                FIN, MachinePointerInfo(SV), false, false, 0);
15649   MemOps.push_back(Store);
15650
15651   // Store fp_offset
15652   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15653   Store = DAG.getStore(Op.getOperand(0), DL,
15654                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15655                                        MVT::i32),
15656                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15657   MemOps.push_back(Store);
15658
15659   // Store ptr to overflow_arg_area
15660   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15661   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15662   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15663                        MachinePointerInfo(SV, 8),
15664                        false, false, 0);
15665   MemOps.push_back(Store);
15666
15667   // Store ptr to reg_save_area.
15668   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15669       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15670   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15671   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15672       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15673   MemOps.push_back(Store);
15674   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15675 }
15676
15677 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15678   assert(Subtarget->is64Bit() &&
15679          "LowerVAARG only handles 64-bit va_arg!");
15680   assert(Op.getNode()->getNumOperands() == 4);
15681
15682   MachineFunction &MF = DAG.getMachineFunction();
15683   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15684     // The Win64 ABI uses char* instead of a structure.
15685     return DAG.expandVAArg(Op.getNode());
15686
15687   SDValue Chain = Op.getOperand(0);
15688   SDValue SrcPtr = Op.getOperand(1);
15689   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15690   unsigned Align = Op.getConstantOperandVal(3);
15691   SDLoc dl(Op);
15692
15693   EVT ArgVT = Op.getNode()->getValueType(0);
15694   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15695   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15696   uint8_t ArgMode;
15697
15698   // Decide which area this value should be read from.
15699   // TODO: Implement the AMD64 ABI in its entirety. This simple
15700   // selection mechanism works only for the basic types.
15701   if (ArgVT == MVT::f80) {
15702     llvm_unreachable("va_arg for f80 not yet implemented");
15703   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15704     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15705   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15706     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15707   } else {
15708     llvm_unreachable("Unhandled argument type in LowerVAARG");
15709   }
15710
15711   if (ArgMode == 2) {
15712     // Sanity Check: Make sure using fp_offset makes sense.
15713     assert(!Subtarget->useSoftFloat() &&
15714            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15715            Subtarget->hasSSE1());
15716   }
15717
15718   // Insert VAARG_64 node into the DAG
15719   // VAARG_64 returns two values: Variable Argument Address, Chain
15720   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15721                        DAG.getConstant(ArgMode, dl, MVT::i8),
15722                        DAG.getConstant(Align, dl, MVT::i32)};
15723   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15724   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15725                                           VTs, InstOps, MVT::i64,
15726                                           MachinePointerInfo(SV),
15727                                           /*Align=*/0,
15728                                           /*Volatile=*/false,
15729                                           /*ReadMem=*/true,
15730                                           /*WriteMem=*/true);
15731   Chain = VAARG.getValue(1);
15732
15733   // Load the next argument and return it
15734   return DAG.getLoad(ArgVT, dl,
15735                      Chain,
15736                      VAARG,
15737                      MachinePointerInfo(),
15738                      false, false, false, 0);
15739 }
15740
15741 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15742                            SelectionDAG &DAG) {
15743   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15744   // where a va_list is still an i8*.
15745   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15746   if (Subtarget->isCallingConvWin64(
15747         DAG.getMachineFunction().getFunction()->getCallingConv()))
15748     // Probably a Win64 va_copy.
15749     return DAG.expandVACopy(Op.getNode());
15750
15751   SDValue Chain = Op.getOperand(0);
15752   SDValue DstPtr = Op.getOperand(1);
15753   SDValue SrcPtr = Op.getOperand(2);
15754   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15755   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15756   SDLoc DL(Op);
15757
15758   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15759                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15760                        false, false,
15761                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15762 }
15763
15764 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15765 // amount is a constant. Takes immediate version of shift as input.
15766 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15767                                           SDValue SrcOp, uint64_t ShiftAmt,
15768                                           SelectionDAG &DAG) {
15769   MVT ElementType = VT.getVectorElementType();
15770
15771   // Fold this packed shift into its first operand if ShiftAmt is 0.
15772   if (ShiftAmt == 0)
15773     return SrcOp;
15774
15775   // Check for ShiftAmt >= element width
15776   if (ShiftAmt >= ElementType.getSizeInBits()) {
15777     if (Opc == X86ISD::VSRAI)
15778       ShiftAmt = ElementType.getSizeInBits() - 1;
15779     else
15780       return DAG.getConstant(0, dl, VT);
15781   }
15782
15783   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15784          && "Unknown target vector shift-by-constant node");
15785
15786   // Fold this packed vector shift into a build vector if SrcOp is a
15787   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15788   if (VT == SrcOp.getSimpleValueType() &&
15789       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15790     SmallVector<SDValue, 8> Elts;
15791     unsigned NumElts = SrcOp->getNumOperands();
15792     ConstantSDNode *ND;
15793
15794     switch(Opc) {
15795     default: llvm_unreachable(nullptr);
15796     case X86ISD::VSHLI:
15797       for (unsigned i=0; i!=NumElts; ++i) {
15798         SDValue CurrentOp = SrcOp->getOperand(i);
15799         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15800           Elts.push_back(CurrentOp);
15801           continue;
15802         }
15803         ND = cast<ConstantSDNode>(CurrentOp);
15804         const APInt &C = ND->getAPIntValue();
15805         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15806       }
15807       break;
15808     case X86ISD::VSRLI:
15809       for (unsigned i=0; i!=NumElts; ++i) {
15810         SDValue CurrentOp = SrcOp->getOperand(i);
15811         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15812           Elts.push_back(CurrentOp);
15813           continue;
15814         }
15815         ND = cast<ConstantSDNode>(CurrentOp);
15816         const APInt &C = ND->getAPIntValue();
15817         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15818       }
15819       break;
15820     case X86ISD::VSRAI:
15821       for (unsigned i=0; i!=NumElts; ++i) {
15822         SDValue CurrentOp = SrcOp->getOperand(i);
15823         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15824           Elts.push_back(CurrentOp);
15825           continue;
15826         }
15827         ND = cast<ConstantSDNode>(CurrentOp);
15828         const APInt &C = ND->getAPIntValue();
15829         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15830       }
15831       break;
15832     }
15833
15834     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15835   }
15836
15837   return DAG.getNode(Opc, dl, VT, SrcOp,
15838                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15839 }
15840
15841 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15842 // may or may not be a constant. Takes immediate version of shift as input.
15843 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15844                                    SDValue SrcOp, SDValue ShAmt,
15845                                    SelectionDAG &DAG) {
15846   MVT SVT = ShAmt.getSimpleValueType();
15847   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15848
15849   // Catch shift-by-constant.
15850   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15851     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15852                                       CShAmt->getZExtValue(), DAG);
15853
15854   // Change opcode to non-immediate version
15855   switch (Opc) {
15856     default: llvm_unreachable("Unknown target vector shift node");
15857     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15858     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15859     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15860   }
15861
15862   const X86Subtarget &Subtarget =
15863       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15864   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15865       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15866     // Let the shuffle legalizer expand this shift amount node.
15867     SDValue Op0 = ShAmt.getOperand(0);
15868     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15869     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15870   } else {
15871     // Need to build a vector containing shift amount.
15872     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15873     SmallVector<SDValue, 4> ShOps;
15874     ShOps.push_back(ShAmt);
15875     if (SVT == MVT::i32) {
15876       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15877       ShOps.push_back(DAG.getUNDEF(SVT));
15878     }
15879     ShOps.push_back(DAG.getUNDEF(SVT));
15880
15881     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15882     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15883   }
15884
15885   // The return type has to be a 128-bit type with the same element
15886   // type as the input type.
15887   MVT EltVT = VT.getVectorElementType();
15888   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15889
15890   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15891   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15892 }
15893
15894 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15895 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15896 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15897 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15898                                     SDValue PreservedSrc,
15899                                     const X86Subtarget *Subtarget,
15900                                     SelectionDAG &DAG) {
15901     EVT VT = Op.getValueType();
15902     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15903                                   MVT::i1, VT.getVectorNumElements());
15904     SDValue VMask = SDValue();
15905     unsigned OpcodeSelect = ISD::VSELECT;
15906     SDLoc dl(Op);
15907
15908     assert(MaskVT.isSimple() && "invalid mask type");
15909
15910     if (isAllOnes(Mask))
15911       return Op;
15912
15913     if (MaskVT.bitsGT(Mask.getValueType())) {
15914       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15915                                          MaskVT.getSizeInBits());
15916       VMask = DAG.getBitcast(MaskVT,
15917                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15918     } else {
15919       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15920                                        Mask.getValueType().getSizeInBits());
15921       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15922       // are extracted by EXTRACT_SUBVECTOR.
15923       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15924                           DAG.getBitcast(BitcastVT, Mask),
15925                           DAG.getIntPtrConstant(0, dl));
15926     }
15927
15928     switch (Op.getOpcode()) {
15929       default: break;
15930       case X86ISD::PCMPEQM:
15931       case X86ISD::PCMPGTM:
15932       case X86ISD::CMPM:
15933       case X86ISD::CMPMU:
15934         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15935       case X86ISD::VFPCLASS:
15936         return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15937       case X86ISD::VTRUNC:
15938       case X86ISD::VTRUNCS:
15939       case X86ISD::VTRUNCUS:
15940         // We can't use ISD::VSELECT here because it is not always "Legal"
15941         // for the destination type. For example vpmovqb require only AVX512
15942         // and vselect that can operate on byte element type require BWI
15943         OpcodeSelect = X86ISD::SELECT;
15944         break;
15945     }
15946     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15947       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15948     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15949 }
15950
15951 /// \brief Creates an SDNode for a predicated scalar operation.
15952 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15953 /// The mask is coming as MVT::i8 and it should be truncated
15954 /// to MVT::i1 while lowering masking intrinsics.
15955 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15956 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15957 /// for a scalar instruction.
15958 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15959                                     SDValue PreservedSrc,
15960                                     const X86Subtarget *Subtarget,
15961                                     SelectionDAG &DAG) {
15962   if (isAllOnes(Mask))
15963     return Op;
15964
15965   EVT VT = Op.getValueType();
15966   SDLoc dl(Op);
15967   // The mask should be of type MVT::i1
15968   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15969
15970   if (Op.getOpcode() == X86ISD::FSETCC)
15971     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15972   if (Op.getOpcode() == X86ISD::VFPCLASS)
15973     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
15974
15975   if (PreservedSrc.getOpcode() == ISD::UNDEF)
15976     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15977   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15978 }
15979
15980 static int getSEHRegistrationNodeSize(const Function *Fn) {
15981   if (!Fn->hasPersonalityFn())
15982     report_fatal_error(
15983         "querying registration node size for function without personality");
15984   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15985   // WinEHStatePass for the full struct definition.
15986   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15987   case EHPersonality::MSVC_X86SEH: return 24;
15988   case EHPersonality::MSVC_CXX: return 16;
15989   default: break;
15990   }
15991   report_fatal_error("can only recover FP for MSVC EH personality functions");
15992 }
15993
15994 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15995 /// function or when returning to a parent frame after catching an exception, we
15996 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15997 /// Here's the math:
15998 ///   RegNodeBase = EntryEBP - RegNodeSize
15999 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
16000 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16001 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16002 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16003                                    SDValue EntryEBP) {
16004   MachineFunction &MF = DAG.getMachineFunction();
16005   SDLoc dl;
16006
16007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16008   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16009
16010   // It's possible that the parent function no longer has a personality function
16011   // if the exceptional code was optimized away, in which case we just return
16012   // the incoming EBP.
16013   if (!Fn->hasPersonalityFn())
16014     return EntryEBP;
16015
16016   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16017
16018   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16019   // registration.
16020   MCSymbol *OffsetSym =
16021       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16022           GlobalValue::getRealLinkageName(Fn->getName()));
16023   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16024   SDValue RegNodeFrameOffset =
16025       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16026
16027   // RegNodeBase = EntryEBP - RegNodeSize
16028   // ParentFP = RegNodeBase - RegNodeFrameOffset
16029   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16030                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16031   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16032 }
16033
16034 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16035                                        SelectionDAG &DAG) {
16036   SDLoc dl(Op);
16037   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16038   EVT VT = Op.getValueType();
16039   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16040   if (IntrData) {
16041     switch(IntrData->Type) {
16042     case INTR_TYPE_1OP:
16043       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16044     case INTR_TYPE_2OP:
16045       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16046         Op.getOperand(2));
16047     case INTR_TYPE_2OP_IMM8:
16048       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16049                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16050     case INTR_TYPE_3OP:
16051       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16052         Op.getOperand(2), Op.getOperand(3));
16053     case INTR_TYPE_4OP:
16054       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16055         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16056     case INTR_TYPE_1OP_MASK_RM: {
16057       SDValue Src = Op.getOperand(1);
16058       SDValue PassThru = Op.getOperand(2);
16059       SDValue Mask = Op.getOperand(3);
16060       SDValue RoundingMode;
16061       // We allways add rounding mode to the Node.
16062       // If the rounding mode is not specified, we add the
16063       // "current direction" mode.
16064       if (Op.getNumOperands() == 4)
16065         RoundingMode =
16066           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16067       else
16068         RoundingMode = Op.getOperand(4);
16069       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16070       if (IntrWithRoundingModeOpcode != 0)
16071         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16072             X86::STATIC_ROUNDING::CUR_DIRECTION)
16073           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16074                                       dl, Op.getValueType(), Src, RoundingMode),
16075                                       Mask, PassThru, Subtarget, DAG);
16076       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16077                                               RoundingMode),
16078                                   Mask, PassThru, Subtarget, DAG);
16079     }
16080     case INTR_TYPE_1OP_MASK: {
16081       SDValue Src = Op.getOperand(1);
16082       SDValue PassThru = Op.getOperand(2);
16083       SDValue Mask = Op.getOperand(3);
16084       // We add rounding mode to the Node when
16085       //   - RM Opcode is specified and
16086       //   - RM is not "current direction".
16087       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16088       if (IntrWithRoundingModeOpcode != 0) {
16089         SDValue Rnd = Op.getOperand(4);
16090         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16091         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16092           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16093                                       dl, Op.getValueType(),
16094                                       Src, Rnd),
16095                                       Mask, PassThru, Subtarget, DAG);
16096         }
16097       }
16098       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16099                                   Mask, PassThru, Subtarget, DAG);
16100     }
16101     case INTR_TYPE_SCALAR_MASK: {
16102       SDValue Src1 = Op.getOperand(1);
16103       SDValue Src2 = Op.getOperand(2);
16104       SDValue passThru = Op.getOperand(3);
16105       SDValue Mask = Op.getOperand(4);
16106       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16107                                   Mask, passThru, Subtarget, DAG);
16108     }
16109     case INTR_TYPE_SCALAR_MASK_RM: {
16110       SDValue Src1 = Op.getOperand(1);
16111       SDValue Src2 = Op.getOperand(2);
16112       SDValue Src0 = Op.getOperand(3);
16113       SDValue Mask = Op.getOperand(4);
16114       // There are 2 kinds of intrinsics in this group:
16115       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16116       // (2) With rounding mode and sae - 7 operands.
16117       if (Op.getNumOperands() == 6) {
16118         SDValue Sae  = Op.getOperand(5);
16119         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16120         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16121                                                 Sae),
16122                                     Mask, Src0, Subtarget, DAG);
16123       }
16124       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16125       SDValue RoundingMode  = Op.getOperand(5);
16126       SDValue Sae  = Op.getOperand(6);
16127       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16128                                               RoundingMode, Sae),
16129                                   Mask, Src0, Subtarget, DAG);
16130     }
16131     case INTR_TYPE_2OP_MASK:
16132     case INTR_TYPE_2OP_IMM8_MASK: {
16133       SDValue Src1 = Op.getOperand(1);
16134       SDValue Src2 = Op.getOperand(2);
16135       SDValue PassThru = Op.getOperand(3);
16136       SDValue Mask = Op.getOperand(4);
16137
16138       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16139         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16140
16141       // We specify 2 possible opcodes for intrinsics with rounding modes.
16142       // First, we check if the intrinsic may have non-default rounding mode,
16143       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16144       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16145       if (IntrWithRoundingModeOpcode != 0) {
16146         SDValue Rnd = Op.getOperand(5);
16147         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16148         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16149           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16150                                       dl, Op.getValueType(),
16151                                       Src1, Src2, Rnd),
16152                                       Mask, PassThru, Subtarget, DAG);
16153         }
16154       }
16155       // TODO: Intrinsics should have fast-math-flags to propagate.
16156       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16157                                   Mask, PassThru, Subtarget, DAG);
16158     }
16159     case INTR_TYPE_2OP_MASK_RM: {
16160       SDValue Src1 = Op.getOperand(1);
16161       SDValue Src2 = Op.getOperand(2);
16162       SDValue PassThru = Op.getOperand(3);
16163       SDValue Mask = Op.getOperand(4);
16164       // We specify 2 possible modes for intrinsics, with/without rounding
16165       // modes.
16166       // First, we check if the intrinsic have rounding mode (6 operands),
16167       // if not, we set rounding mode to "current".
16168       SDValue Rnd;
16169       if (Op.getNumOperands() == 6)
16170         Rnd = Op.getOperand(5);
16171       else
16172         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16173       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16174                                               Src1, Src2, Rnd),
16175                                   Mask, PassThru, Subtarget, DAG);
16176     }
16177     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16178       SDValue Src1 = Op.getOperand(1);
16179       SDValue Src2 = Op.getOperand(2);
16180       SDValue Src3 = Op.getOperand(3);
16181       SDValue PassThru = Op.getOperand(4);
16182       SDValue Mask = Op.getOperand(5);
16183       SDValue Sae  = Op.getOperand(6);
16184
16185       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16186                                               Src2, Src3, Sae),
16187                                   Mask, PassThru, Subtarget, DAG);
16188     }
16189     case INTR_TYPE_3OP_MASK_RM: {
16190       SDValue Src1 = Op.getOperand(1);
16191       SDValue Src2 = Op.getOperand(2);
16192       SDValue Imm = Op.getOperand(3);
16193       SDValue PassThru = Op.getOperand(4);
16194       SDValue Mask = Op.getOperand(5);
16195       // We specify 2 possible modes for intrinsics, with/without rounding
16196       // modes.
16197       // First, we check if the intrinsic have rounding mode (7 operands),
16198       // if not, we set rounding mode to "current".
16199       SDValue Rnd;
16200       if (Op.getNumOperands() == 7)
16201         Rnd = Op.getOperand(6);
16202       else
16203         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16204       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16205         Src1, Src2, Imm, Rnd),
16206         Mask, PassThru, Subtarget, DAG);
16207     }
16208     case INTR_TYPE_3OP_IMM8_MASK:
16209     case INTR_TYPE_3OP_MASK:
16210     case INSERT_SUBVEC: {
16211       SDValue Src1 = Op.getOperand(1);
16212       SDValue Src2 = Op.getOperand(2);
16213       SDValue Src3 = Op.getOperand(3);
16214       SDValue PassThru = Op.getOperand(4);
16215       SDValue Mask = Op.getOperand(5);
16216
16217       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16218         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16219       else if (IntrData->Type == INSERT_SUBVEC) {
16220         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16221         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16222         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16223         Imm *= Src2.getValueType().getVectorNumElements();
16224         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16225       }
16226
16227       // We specify 2 possible opcodes for intrinsics with rounding modes.
16228       // First, we check if the intrinsic may have non-default rounding mode,
16229       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16230       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16231       if (IntrWithRoundingModeOpcode != 0) {
16232         SDValue Rnd = Op.getOperand(6);
16233         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16234         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16235           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16236                                       dl, Op.getValueType(),
16237                                       Src1, Src2, Src3, Rnd),
16238                                       Mask, PassThru, Subtarget, DAG);
16239         }
16240       }
16241       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16242                                               Src1, Src2, Src3),
16243                                   Mask, PassThru, Subtarget, DAG);
16244     }
16245     case VPERM_3OP_MASKZ:
16246     case VPERM_3OP_MASK:
16247     case FMA_OP_MASK3:
16248     case FMA_OP_MASKZ:
16249     case FMA_OP_MASK: {
16250       SDValue Src1 = Op.getOperand(1);
16251       SDValue Src2 = Op.getOperand(2);
16252       SDValue Src3 = Op.getOperand(3);
16253       SDValue Mask = Op.getOperand(4);
16254       EVT VT = Op.getValueType();
16255       SDValue PassThru = SDValue();
16256
16257       // set PassThru element
16258       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16259         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16260       else if (IntrData->Type == FMA_OP_MASK3)
16261         PassThru = Src3;
16262       else
16263         PassThru = Src1;
16264
16265       // We specify 2 possible opcodes for intrinsics with rounding modes.
16266       // First, we check if the intrinsic may have non-default rounding mode,
16267       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16268       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16269       if (IntrWithRoundingModeOpcode != 0) {
16270         SDValue Rnd = Op.getOperand(5);
16271         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16272             X86::STATIC_ROUNDING::CUR_DIRECTION)
16273           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16274                                                   dl, Op.getValueType(),
16275                                                   Src1, Src2, Src3, Rnd),
16276                                       Mask, PassThru, Subtarget, DAG);
16277       }
16278       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16279                                               dl, Op.getValueType(),
16280                                               Src1, Src2, Src3),
16281                                   Mask, PassThru, Subtarget, DAG);
16282     }
16283     case TERLOG_OP_MASK:
16284     case TERLOG_OP_MASKZ: {
16285       SDValue Src1 = Op.getOperand(1);
16286       SDValue Src2 = Op.getOperand(2);
16287       SDValue Src3 = Op.getOperand(3);
16288       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16289       SDValue Mask = Op.getOperand(5);
16290       EVT VT = Op.getValueType();
16291       SDValue PassThru = Src1;
16292       // Set PassThru element.
16293       if (IntrData->Type == TERLOG_OP_MASKZ)
16294         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16295
16296       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16297                                               Src1, Src2, Src3, Src4),
16298                                   Mask, PassThru, Subtarget, DAG);
16299     }
16300     case FPCLASS: {
16301       // FPclass intrinsics with mask
16302        SDValue Src1 = Op.getOperand(1);
16303        EVT VT = Src1.getValueType();
16304        EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16305                                       VT.getVectorNumElements());
16306        SDValue Imm = Op.getOperand(2);
16307        SDValue Mask = Op.getOperand(3);
16308        EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16309                                         Mask.getValueType().getSizeInBits());
16310        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16311        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16312                                                  DAG.getTargetConstant(0, dl, MaskVT),
16313                                                  Subtarget, DAG);
16314        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16315                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16316                                  DAG.getIntPtrConstant(0, dl));
16317        return DAG.getBitcast(Op.getValueType(), Res);
16318     }
16319     case FPCLASSS: {
16320       SDValue Src1 = Op.getOperand(1);
16321       SDValue Imm = Op.getOperand(2);
16322       SDValue Mask = Op.getOperand(3);
16323       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16324       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16325         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16326       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16327     }
16328     case CMP_MASK:
16329     case CMP_MASK_CC: {
16330       // Comparison intrinsics with masks.
16331       // Example of transformation:
16332       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16333       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16334       // (i8 (bitcast
16335       //   (v8i1 (insert_subvector undef,
16336       //           (v2i1 (and (PCMPEQM %a, %b),
16337       //                      (extract_subvector
16338       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16339       EVT VT = Op.getOperand(1).getValueType();
16340       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16341                                     VT.getVectorNumElements());
16342       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16343       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16344                                        Mask.getValueType().getSizeInBits());
16345       SDValue Cmp;
16346       if (IntrData->Type == CMP_MASK_CC) {
16347         SDValue CC = Op.getOperand(3);
16348         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16349         // We specify 2 possible opcodes for intrinsics with rounding modes.
16350         // First, we check if the intrinsic may have non-default rounding mode,
16351         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16352         if (IntrData->Opc1 != 0) {
16353           SDValue Rnd = Op.getOperand(5);
16354           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16355               X86::STATIC_ROUNDING::CUR_DIRECTION)
16356             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16357                               Op.getOperand(2), CC, Rnd);
16358         }
16359         //default rounding mode
16360         if(!Cmp.getNode())
16361             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16362                               Op.getOperand(2), CC);
16363
16364       } else {
16365         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16366         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16367                           Op.getOperand(2));
16368       }
16369       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16370                                              DAG.getTargetConstant(0, dl,
16371                                                                    MaskVT),
16372                                              Subtarget, DAG);
16373       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16374                                 DAG.getUNDEF(BitcastVT), CmpMask,
16375                                 DAG.getIntPtrConstant(0, dl));
16376       return DAG.getBitcast(Op.getValueType(), Res);
16377     }
16378     case CMP_MASK_SCALAR_CC: {
16379       SDValue Src1 = Op.getOperand(1);
16380       SDValue Src2 = Op.getOperand(2);
16381       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16382       SDValue Mask = Op.getOperand(4);
16383
16384       SDValue Cmp;
16385       if (IntrData->Opc1 != 0) {
16386         SDValue Rnd = Op.getOperand(5);
16387         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16388             X86::STATIC_ROUNDING::CUR_DIRECTION)
16389           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16390       }
16391       //default rounding mode
16392       if(!Cmp.getNode())
16393         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16394
16395       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16396                                              DAG.getTargetConstant(0, dl,
16397                                                                    MVT::i1),
16398                                              Subtarget, DAG);
16399
16400       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16401                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16402                          DAG.getValueType(MVT::i1));
16403     }
16404     case COMI: { // Comparison intrinsics
16405       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16406       SDValue LHS = Op.getOperand(1);
16407       SDValue RHS = Op.getOperand(2);
16408       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16409       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16410       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16411       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16412                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16413       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16414     }
16415     case VSHIFT:
16416       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16417                                  Op.getOperand(1), Op.getOperand(2), DAG);
16418     case VSHIFT_MASK:
16419       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16420                                                       Op.getSimpleValueType(),
16421                                                       Op.getOperand(1),
16422                                                       Op.getOperand(2), DAG),
16423                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16424                                   DAG);
16425     case COMPRESS_EXPAND_IN_REG: {
16426       SDValue Mask = Op.getOperand(3);
16427       SDValue DataToCompress = Op.getOperand(1);
16428       SDValue PassThru = Op.getOperand(2);
16429       if (isAllOnes(Mask)) // return data as is
16430         return Op.getOperand(1);
16431
16432       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16433                                               DataToCompress),
16434                                   Mask, PassThru, Subtarget, DAG);
16435     }
16436     case BLEND: {
16437       SDValue Mask = Op.getOperand(3);
16438       EVT VT = Op.getValueType();
16439       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16440                                     VT.getVectorNumElements());
16441       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16442                                        Mask.getValueType().getSizeInBits());
16443       SDLoc dl(Op);
16444       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16445                                   DAG.getBitcast(BitcastVT, Mask),
16446                                   DAG.getIntPtrConstant(0, dl));
16447       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16448                          Op.getOperand(2));
16449     }
16450     default:
16451       break;
16452     }
16453   }
16454
16455   switch (IntNo) {
16456   default: return SDValue();    // Don't custom lower most intrinsics.
16457
16458   case Intrinsic::x86_avx2_permd:
16459   case Intrinsic::x86_avx2_permps:
16460     // Operands intentionally swapped. Mask is last operand to intrinsic,
16461     // but second operand for node/instruction.
16462     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16463                        Op.getOperand(2), Op.getOperand(1));
16464
16465   // ptest and testp intrinsics. The intrinsic these come from are designed to
16466   // return an integer value, not just an instruction so lower it to the ptest
16467   // or testp pattern and a setcc for the result.
16468   case Intrinsic::x86_sse41_ptestz:
16469   case Intrinsic::x86_sse41_ptestc:
16470   case Intrinsic::x86_sse41_ptestnzc:
16471   case Intrinsic::x86_avx_ptestz_256:
16472   case Intrinsic::x86_avx_ptestc_256:
16473   case Intrinsic::x86_avx_ptestnzc_256:
16474   case Intrinsic::x86_avx_vtestz_ps:
16475   case Intrinsic::x86_avx_vtestc_ps:
16476   case Intrinsic::x86_avx_vtestnzc_ps:
16477   case Intrinsic::x86_avx_vtestz_pd:
16478   case Intrinsic::x86_avx_vtestc_pd:
16479   case Intrinsic::x86_avx_vtestnzc_pd:
16480   case Intrinsic::x86_avx_vtestz_ps_256:
16481   case Intrinsic::x86_avx_vtestc_ps_256:
16482   case Intrinsic::x86_avx_vtestnzc_ps_256:
16483   case Intrinsic::x86_avx_vtestz_pd_256:
16484   case Intrinsic::x86_avx_vtestc_pd_256:
16485   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16486     bool IsTestPacked = false;
16487     unsigned X86CC;
16488     switch (IntNo) {
16489     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16490     case Intrinsic::x86_avx_vtestz_ps:
16491     case Intrinsic::x86_avx_vtestz_pd:
16492     case Intrinsic::x86_avx_vtestz_ps_256:
16493     case Intrinsic::x86_avx_vtestz_pd_256:
16494       IsTestPacked = true; // Fallthrough
16495     case Intrinsic::x86_sse41_ptestz:
16496     case Intrinsic::x86_avx_ptestz_256:
16497       // ZF = 1
16498       X86CC = X86::COND_E;
16499       break;
16500     case Intrinsic::x86_avx_vtestc_ps:
16501     case Intrinsic::x86_avx_vtestc_pd:
16502     case Intrinsic::x86_avx_vtestc_ps_256:
16503     case Intrinsic::x86_avx_vtestc_pd_256:
16504       IsTestPacked = true; // Fallthrough
16505     case Intrinsic::x86_sse41_ptestc:
16506     case Intrinsic::x86_avx_ptestc_256:
16507       // CF = 1
16508       X86CC = X86::COND_B;
16509       break;
16510     case Intrinsic::x86_avx_vtestnzc_ps:
16511     case Intrinsic::x86_avx_vtestnzc_pd:
16512     case Intrinsic::x86_avx_vtestnzc_ps_256:
16513     case Intrinsic::x86_avx_vtestnzc_pd_256:
16514       IsTestPacked = true; // Fallthrough
16515     case Intrinsic::x86_sse41_ptestnzc:
16516     case Intrinsic::x86_avx_ptestnzc_256:
16517       // ZF and CF = 0
16518       X86CC = X86::COND_A;
16519       break;
16520     }
16521
16522     SDValue LHS = Op.getOperand(1);
16523     SDValue RHS = Op.getOperand(2);
16524     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16525     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16526     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16527     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16528     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16529   }
16530   case Intrinsic::x86_avx512_kortestz_w:
16531   case Intrinsic::x86_avx512_kortestc_w: {
16532     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16533     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16534     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16535     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16536     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16537     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16538     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16539   }
16540
16541   case Intrinsic::x86_sse42_pcmpistria128:
16542   case Intrinsic::x86_sse42_pcmpestria128:
16543   case Intrinsic::x86_sse42_pcmpistric128:
16544   case Intrinsic::x86_sse42_pcmpestric128:
16545   case Intrinsic::x86_sse42_pcmpistrio128:
16546   case Intrinsic::x86_sse42_pcmpestrio128:
16547   case Intrinsic::x86_sse42_pcmpistris128:
16548   case Intrinsic::x86_sse42_pcmpestris128:
16549   case Intrinsic::x86_sse42_pcmpistriz128:
16550   case Intrinsic::x86_sse42_pcmpestriz128: {
16551     unsigned Opcode;
16552     unsigned X86CC;
16553     switch (IntNo) {
16554     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16555     case Intrinsic::x86_sse42_pcmpistria128:
16556       Opcode = X86ISD::PCMPISTRI;
16557       X86CC = X86::COND_A;
16558       break;
16559     case Intrinsic::x86_sse42_pcmpestria128:
16560       Opcode = X86ISD::PCMPESTRI;
16561       X86CC = X86::COND_A;
16562       break;
16563     case Intrinsic::x86_sse42_pcmpistric128:
16564       Opcode = X86ISD::PCMPISTRI;
16565       X86CC = X86::COND_B;
16566       break;
16567     case Intrinsic::x86_sse42_pcmpestric128:
16568       Opcode = X86ISD::PCMPESTRI;
16569       X86CC = X86::COND_B;
16570       break;
16571     case Intrinsic::x86_sse42_pcmpistrio128:
16572       Opcode = X86ISD::PCMPISTRI;
16573       X86CC = X86::COND_O;
16574       break;
16575     case Intrinsic::x86_sse42_pcmpestrio128:
16576       Opcode = X86ISD::PCMPESTRI;
16577       X86CC = X86::COND_O;
16578       break;
16579     case Intrinsic::x86_sse42_pcmpistris128:
16580       Opcode = X86ISD::PCMPISTRI;
16581       X86CC = X86::COND_S;
16582       break;
16583     case Intrinsic::x86_sse42_pcmpestris128:
16584       Opcode = X86ISD::PCMPESTRI;
16585       X86CC = X86::COND_S;
16586       break;
16587     case Intrinsic::x86_sse42_pcmpistriz128:
16588       Opcode = X86ISD::PCMPISTRI;
16589       X86CC = X86::COND_E;
16590       break;
16591     case Intrinsic::x86_sse42_pcmpestriz128:
16592       Opcode = X86ISD::PCMPESTRI;
16593       X86CC = X86::COND_E;
16594       break;
16595     }
16596     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16597     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16598     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16599     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16600                                 DAG.getConstant(X86CC, dl, MVT::i8),
16601                                 SDValue(PCMP.getNode(), 1));
16602     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16603   }
16604
16605   case Intrinsic::x86_sse42_pcmpistri128:
16606   case Intrinsic::x86_sse42_pcmpestri128: {
16607     unsigned Opcode;
16608     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16609       Opcode = X86ISD::PCMPISTRI;
16610     else
16611       Opcode = X86ISD::PCMPESTRI;
16612
16613     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16614     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16615     return DAG.getNode(Opcode, dl, VTs, NewOps);
16616   }
16617
16618   case Intrinsic::x86_seh_lsda: {
16619     // Compute the symbol for the LSDA. We know it'll get emitted later.
16620     MachineFunction &MF = DAG.getMachineFunction();
16621     SDValue Op1 = Op.getOperand(1);
16622     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16623     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16624         GlobalValue::getRealLinkageName(Fn->getName()));
16625
16626     // Generate a simple absolute symbol reference. This intrinsic is only
16627     // supported on 32-bit Windows, which isn't PIC.
16628     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16629     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16630   }
16631
16632   case Intrinsic::x86_seh_recoverfp: {
16633     SDValue FnOp = Op.getOperand(1);
16634     SDValue IncomingFPOp = Op.getOperand(2);
16635     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16636     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16637     if (!Fn)
16638       report_fatal_error(
16639           "llvm.x86.seh.recoverfp must take a function as the first argument");
16640     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16641   }
16642
16643   case Intrinsic::localaddress: {
16644     // Returns one of the stack, base, or frame pointer registers, depending on
16645     // which is used to reference local variables.
16646     MachineFunction &MF = DAG.getMachineFunction();
16647     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16648     unsigned Reg;
16649     if (RegInfo->hasBasePointer(MF))
16650       Reg = RegInfo->getBaseRegister();
16651     else // This function handles the SP or FP case.
16652       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16653     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16654   }
16655   }
16656 }
16657
16658 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16659                               SDValue Src, SDValue Mask, SDValue Base,
16660                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16661                               const X86Subtarget * Subtarget) {
16662   SDLoc dl(Op);
16663   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16664   if (!C)
16665     llvm_unreachable("Invalid scale type");
16666   unsigned ScaleVal = C->getZExtValue();
16667   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16668     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16669
16670   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16671   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16672                              Index.getSimpleValueType().getVectorNumElements());
16673   SDValue MaskInReg;
16674   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16675   if (MaskC)
16676     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16677   else {
16678     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16679                                      Mask.getValueType().getSizeInBits());
16680
16681     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16682     // are extracted by EXTRACT_SUBVECTOR.
16683     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16684                             DAG.getBitcast(BitcastVT, Mask),
16685                             DAG.getIntPtrConstant(0, dl));
16686   }
16687   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16688   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16689   SDValue Segment = DAG.getRegister(0, MVT::i32);
16690   if (Src.getOpcode() == ISD::UNDEF)
16691     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16692   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16693   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16694   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16695   return DAG.getMergeValues(RetOps, dl);
16696 }
16697
16698 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16699                                SDValue Src, SDValue Mask, SDValue Base,
16700                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16701   SDLoc dl(Op);
16702   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16703   if (!C)
16704     llvm_unreachable("Invalid scale type");
16705   unsigned ScaleVal = C->getZExtValue();
16706   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16707     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16708
16709   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16710   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16711   SDValue Segment = DAG.getRegister(0, MVT::i32);
16712   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16713                              Index.getSimpleValueType().getVectorNumElements());
16714   SDValue MaskInReg;
16715   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16716   if (MaskC)
16717     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16718   else {
16719     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16720                                      Mask.getValueType().getSizeInBits());
16721
16722     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16723     // are extracted by EXTRACT_SUBVECTOR.
16724     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16725                             DAG.getBitcast(BitcastVT, Mask),
16726                             DAG.getIntPtrConstant(0, dl));
16727   }
16728   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16729   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16730   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16731   return SDValue(Res, 1);
16732 }
16733
16734 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16735                                SDValue Mask, SDValue Base, SDValue Index,
16736                                SDValue ScaleOp, SDValue Chain) {
16737   SDLoc dl(Op);
16738   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16739   assert(C && "Invalid scale type");
16740   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16741   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16742   SDValue Segment = DAG.getRegister(0, MVT::i32);
16743   EVT MaskVT =
16744     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16745   SDValue MaskInReg;
16746   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16747   if (MaskC)
16748     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16749   else
16750     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16751   //SDVTList VTs = DAG.getVTList(MVT::Other);
16752   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16753   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16754   return SDValue(Res, 0);
16755 }
16756
16757 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16758 // read performance monitor counters (x86_rdpmc).
16759 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16760                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16761                               SmallVectorImpl<SDValue> &Results) {
16762   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16763   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16764   SDValue LO, HI;
16765
16766   // The ECX register is used to select the index of the performance counter
16767   // to read.
16768   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16769                                    N->getOperand(2));
16770   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16771
16772   // Reads the content of a 64-bit performance counter and returns it in the
16773   // registers EDX:EAX.
16774   if (Subtarget->is64Bit()) {
16775     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16776     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16777                             LO.getValue(2));
16778   } else {
16779     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16780     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16781                             LO.getValue(2));
16782   }
16783   Chain = HI.getValue(1);
16784
16785   if (Subtarget->is64Bit()) {
16786     // The EAX register is loaded with the low-order 32 bits. The EDX register
16787     // is loaded with the supported high-order bits of the counter.
16788     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16789                               DAG.getConstant(32, DL, MVT::i8));
16790     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16791     Results.push_back(Chain);
16792     return;
16793   }
16794
16795   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16796   SDValue Ops[] = { LO, HI };
16797   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16798   Results.push_back(Pair);
16799   Results.push_back(Chain);
16800 }
16801
16802 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16803 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16804 // also used to custom lower READCYCLECOUNTER nodes.
16805 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16806                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16807                               SmallVectorImpl<SDValue> &Results) {
16808   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16809   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16810   SDValue LO, HI;
16811
16812   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16813   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16814   // and the EAX register is loaded with the low-order 32 bits.
16815   if (Subtarget->is64Bit()) {
16816     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16817     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16818                             LO.getValue(2));
16819   } else {
16820     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16821     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16822                             LO.getValue(2));
16823   }
16824   SDValue Chain = HI.getValue(1);
16825
16826   if (Opcode == X86ISD::RDTSCP_DAG) {
16827     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16828
16829     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16830     // the ECX register. Add 'ecx' explicitly to the chain.
16831     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16832                                      HI.getValue(2));
16833     // Explicitly store the content of ECX at the location passed in input
16834     // to the 'rdtscp' intrinsic.
16835     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16836                          MachinePointerInfo(), false, false, 0);
16837   }
16838
16839   if (Subtarget->is64Bit()) {
16840     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16841     // the EAX register is loaded with the low-order 32 bits.
16842     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16843                               DAG.getConstant(32, DL, MVT::i8));
16844     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16845     Results.push_back(Chain);
16846     return;
16847   }
16848
16849   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16850   SDValue Ops[] = { LO, HI };
16851   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16852   Results.push_back(Pair);
16853   Results.push_back(Chain);
16854 }
16855
16856 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16857                                      SelectionDAG &DAG) {
16858   SmallVector<SDValue, 2> Results;
16859   SDLoc DL(Op);
16860   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16861                           Results);
16862   return DAG.getMergeValues(Results, DL);
16863 }
16864
16865 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16866                                     SelectionDAG &DAG) {
16867   MachineFunction &MF = DAG.getMachineFunction();
16868   const Function *Fn = MF.getFunction();
16869   SDLoc dl(Op);
16870   SDValue Chain = Op.getOperand(0);
16871
16872   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16873          "using llvm.x86.seh.restoreframe requires a frame pointer");
16874
16875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16876   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16877
16878   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16879   unsigned FrameReg =
16880       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16881   unsigned SPReg = RegInfo->getStackRegister();
16882   unsigned SlotSize = RegInfo->getSlotSize();
16883
16884   // Get incoming EBP.
16885   SDValue IncomingEBP =
16886       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16887
16888   // SP is saved in the first field of every registration node, so load
16889   // [EBP-RegNodeSize] into SP.
16890   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16891   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16892                                DAG.getConstant(-RegNodeSize, dl, VT));
16893   SDValue NewSP =
16894       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16895                   false, VT.getScalarSizeInBits() / 8);
16896   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16897
16898   if (!RegInfo->needsStackRealignment(MF)) {
16899     // Adjust EBP to point back to the original frame position.
16900     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16901     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16902   } else {
16903     assert(RegInfo->hasBasePointer(MF) &&
16904            "functions with Win32 EH must use frame or base pointer register");
16905
16906     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16907     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16908     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16909
16910     // Reload the spilled EBP value, now that the stack and base pointers are
16911     // set up.
16912     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16913     X86FI->setHasSEHFramePtrSave(true);
16914     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16915     X86FI->setSEHFramePtrSaveIndex(FI);
16916     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16917                                 MachinePointerInfo(), false, false, false,
16918                                 VT.getScalarSizeInBits() / 8);
16919     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16920   }
16921
16922   return Chain;
16923 }
16924
16925 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16926 /// return truncate Store/MaskedStore Node
16927 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16928                                                SelectionDAG &DAG,
16929                                                MVT ElementType) {
16930   SDLoc dl(Op);
16931   SDValue Mask = Op.getOperand(4);
16932   SDValue DataToTruncate = Op.getOperand(3);
16933   SDValue Addr = Op.getOperand(2);
16934   SDValue Chain = Op.getOperand(0);
16935
16936   EVT VT  = DataToTruncate.getValueType();
16937   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16938                              ElementType, VT.getVectorNumElements());
16939
16940   if (isAllOnes(Mask)) // return just a truncate store
16941     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16942                              MachinePointerInfo(), SVT, false, false,
16943                              SVT.getScalarSizeInBits()/8);
16944
16945   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16946                                 MVT::i1, VT.getVectorNumElements());
16947   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16948                                    Mask.getValueType().getSizeInBits());
16949   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16950   // are extracted by EXTRACT_SUBVECTOR.
16951   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16952                               DAG.getBitcast(BitcastVT, Mask),
16953                               DAG.getIntPtrConstant(0, dl));
16954
16955   MachineMemOperand *MMO = DAG.getMachineFunction().
16956     getMachineMemOperand(MachinePointerInfo(),
16957                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16958                          SVT.getScalarSizeInBits()/8);
16959
16960   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16961                             VMask, SVT, MMO, true);
16962 }
16963
16964 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16965                                       SelectionDAG &DAG) {
16966   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16967
16968   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16969   if (!IntrData) {
16970     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16971       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16972     return SDValue();
16973   }
16974
16975   SDLoc dl(Op);
16976   switch(IntrData->Type) {
16977   default:
16978     llvm_unreachable("Unknown Intrinsic Type");
16979     break;
16980   case RDSEED:
16981   case RDRAND: {
16982     // Emit the node with the right value type.
16983     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16984     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16985
16986     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16987     // Otherwise return the value from Rand, which is always 0, casted to i32.
16988     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16989                       DAG.getConstant(1, dl, Op->getValueType(1)),
16990                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16991                       SDValue(Result.getNode(), 1) };
16992     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16993                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16994                                   Ops);
16995
16996     // Return { result, isValid, chain }.
16997     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16998                        SDValue(Result.getNode(), 2));
16999   }
17000   case GATHER: {
17001   //gather(v1, mask, index, base, scale);
17002     SDValue Chain = Op.getOperand(0);
17003     SDValue Src   = Op.getOperand(2);
17004     SDValue Base  = Op.getOperand(3);
17005     SDValue Index = Op.getOperand(4);
17006     SDValue Mask  = Op.getOperand(5);
17007     SDValue Scale = Op.getOperand(6);
17008     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17009                          Chain, Subtarget);
17010   }
17011   case SCATTER: {
17012   //scatter(base, mask, index, v1, scale);
17013     SDValue Chain = Op.getOperand(0);
17014     SDValue Base  = Op.getOperand(2);
17015     SDValue Mask  = Op.getOperand(3);
17016     SDValue Index = Op.getOperand(4);
17017     SDValue Src   = Op.getOperand(5);
17018     SDValue Scale = Op.getOperand(6);
17019     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17020                           Scale, Chain);
17021   }
17022   case PREFETCH: {
17023     SDValue Hint = Op.getOperand(6);
17024     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17025     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17026     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17027     SDValue Chain = Op.getOperand(0);
17028     SDValue Mask  = Op.getOperand(2);
17029     SDValue Index = Op.getOperand(3);
17030     SDValue Base  = Op.getOperand(4);
17031     SDValue Scale = Op.getOperand(5);
17032     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17033   }
17034   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17035   case RDTSC: {
17036     SmallVector<SDValue, 2> Results;
17037     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17038                             Results);
17039     return DAG.getMergeValues(Results, dl);
17040   }
17041   // Read Performance Monitoring Counters.
17042   case RDPMC: {
17043     SmallVector<SDValue, 2> Results;
17044     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17045     return DAG.getMergeValues(Results, dl);
17046   }
17047   // XTEST intrinsics.
17048   case XTEST: {
17049     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17050     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17051     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17052                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17053                                 InTrans);
17054     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17055     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17056                        Ret, SDValue(InTrans.getNode(), 1));
17057   }
17058   // ADC/ADCX/SBB
17059   case ADX: {
17060     SmallVector<SDValue, 2> Results;
17061     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17062     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17063     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17064                                 DAG.getConstant(-1, dl, MVT::i8));
17065     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17066                               Op.getOperand(4), GenCF.getValue(1));
17067     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17068                                  Op.getOperand(5), MachinePointerInfo(),
17069                                  false, false, 0);
17070     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17071                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17072                                 Res.getValue(1));
17073     Results.push_back(SetCC);
17074     Results.push_back(Store);
17075     return DAG.getMergeValues(Results, dl);
17076   }
17077   case COMPRESS_TO_MEM: {
17078     SDLoc dl(Op);
17079     SDValue Mask = Op.getOperand(4);
17080     SDValue DataToCompress = Op.getOperand(3);
17081     SDValue Addr = Op.getOperand(2);
17082     SDValue Chain = Op.getOperand(0);
17083
17084     EVT VT = DataToCompress.getValueType();
17085     if (isAllOnes(Mask)) // return just a store
17086       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17087                           MachinePointerInfo(), false, false,
17088                           VT.getScalarSizeInBits()/8);
17089
17090     SDValue Compressed =
17091       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17092                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17093     return DAG.getStore(Chain, dl, Compressed, Addr,
17094                         MachinePointerInfo(), false, false,
17095                         VT.getScalarSizeInBits()/8);
17096   }
17097   case TRUNCATE_TO_MEM_VI8:
17098     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17099   case TRUNCATE_TO_MEM_VI16:
17100     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17101   case TRUNCATE_TO_MEM_VI32:
17102     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17103   case EXPAND_FROM_MEM: {
17104     SDLoc dl(Op);
17105     SDValue Mask = Op.getOperand(4);
17106     SDValue PassThru = Op.getOperand(3);
17107     SDValue Addr = Op.getOperand(2);
17108     SDValue Chain = Op.getOperand(0);
17109     EVT VT = Op.getValueType();
17110
17111     if (isAllOnes(Mask)) // return just a load
17112       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17113                          false, VT.getScalarSizeInBits()/8);
17114
17115     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17116                                        false, false, false,
17117                                        VT.getScalarSizeInBits()/8);
17118
17119     SDValue Results[] = {
17120       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17121                            Mask, PassThru, Subtarget, DAG), Chain};
17122     return DAG.getMergeValues(Results, dl);
17123   }
17124   }
17125 }
17126
17127 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17128                                            SelectionDAG &DAG) const {
17129   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17130   MFI->setReturnAddressIsTaken(true);
17131
17132   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17133     return SDValue();
17134
17135   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17136   SDLoc dl(Op);
17137   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17138
17139   if (Depth > 0) {
17140     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17141     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17142     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17143     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17144                        DAG.getNode(ISD::ADD, dl, PtrVT,
17145                                    FrameAddr, Offset),
17146                        MachinePointerInfo(), false, false, false, 0);
17147   }
17148
17149   // Just load the return address.
17150   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17151   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17152                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17153 }
17154
17155 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17156   MachineFunction &MF = DAG.getMachineFunction();
17157   MachineFrameInfo *MFI = MF.getFrameInfo();
17158   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17159   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17160   EVT VT = Op.getValueType();
17161
17162   MFI->setFrameAddressIsTaken(true);
17163
17164   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17165     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17166     // is not possible to crawl up the stack without looking at the unwind codes
17167     // simultaneously.
17168     int FrameAddrIndex = FuncInfo->getFAIndex();
17169     if (!FrameAddrIndex) {
17170       // Set up a frame object for the return address.
17171       unsigned SlotSize = RegInfo->getSlotSize();
17172       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17173           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17174       FuncInfo->setFAIndex(FrameAddrIndex);
17175     }
17176     return DAG.getFrameIndex(FrameAddrIndex, VT);
17177   }
17178
17179   unsigned FrameReg =
17180       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17181   SDLoc dl(Op);  // FIXME probably not meaningful
17182   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17183   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17184           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17185          "Invalid Frame Register!");
17186   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17187   while (Depth--)
17188     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17189                             MachinePointerInfo(),
17190                             false, false, false, 0);
17191   return FrameAddr;
17192 }
17193
17194 // FIXME? Maybe this could be a TableGen attribute on some registers and
17195 // this table could be generated automatically from RegInfo.
17196 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17197                                               SelectionDAG &DAG) const {
17198   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17199   const MachineFunction &MF = DAG.getMachineFunction();
17200
17201   unsigned Reg = StringSwitch<unsigned>(RegName)
17202                        .Case("esp", X86::ESP)
17203                        .Case("rsp", X86::RSP)
17204                        .Case("ebp", X86::EBP)
17205                        .Case("rbp", X86::RBP)
17206                        .Default(0);
17207
17208   if (Reg == X86::EBP || Reg == X86::RBP) {
17209     if (!TFI.hasFP(MF))
17210       report_fatal_error("register " + StringRef(RegName) +
17211                          " is allocatable: function has no frame pointer");
17212 #ifndef NDEBUG
17213     else {
17214       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17215       unsigned FrameReg =
17216           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17217       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17218              "Invalid Frame Register!");
17219     }
17220 #endif
17221   }
17222
17223   if (Reg)
17224     return Reg;
17225
17226   report_fatal_error("Invalid register name global variable");
17227 }
17228
17229 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17230                                                      SelectionDAG &DAG) const {
17231   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17232   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17233 }
17234
17235 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17236   SDValue Chain     = Op.getOperand(0);
17237   SDValue Offset    = Op.getOperand(1);
17238   SDValue Handler   = Op.getOperand(2);
17239   SDLoc dl      (Op);
17240
17241   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17242   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17243   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17244   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17245           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17246          "Invalid Frame Register!");
17247   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17248   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17249
17250   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17251                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17252                                                        dl));
17253   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17254   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17255                        false, false, 0);
17256   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17257
17258   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17259                      DAG.getRegister(StoreAddrReg, PtrVT));
17260 }
17261
17262 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17263                                                SelectionDAG &DAG) const {
17264   SDLoc DL(Op);
17265   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17266                      DAG.getVTList(MVT::i32, MVT::Other),
17267                      Op.getOperand(0), Op.getOperand(1));
17268 }
17269
17270 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17271                                                 SelectionDAG &DAG) const {
17272   SDLoc DL(Op);
17273   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17274                      Op.getOperand(0), Op.getOperand(1));
17275 }
17276
17277 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17278   return Op.getOperand(0);
17279 }
17280
17281 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17282                                                 SelectionDAG &DAG) const {
17283   SDValue Root = Op.getOperand(0);
17284   SDValue Trmp = Op.getOperand(1); // trampoline
17285   SDValue FPtr = Op.getOperand(2); // nested function
17286   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17287   SDLoc dl (Op);
17288
17289   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17290   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17291
17292   if (Subtarget->is64Bit()) {
17293     SDValue OutChains[6];
17294
17295     // Large code-model.
17296     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17297     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17298
17299     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17300     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17301
17302     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17303
17304     // Load the pointer to the nested function into R11.
17305     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17306     SDValue Addr = Trmp;
17307     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17308                                 Addr, MachinePointerInfo(TrmpAddr),
17309                                 false, false, 0);
17310
17311     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17312                        DAG.getConstant(2, dl, MVT::i64));
17313     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17314                                 MachinePointerInfo(TrmpAddr, 2),
17315                                 false, false, 2);
17316
17317     // Load the 'nest' parameter value into R10.
17318     // R10 is specified in X86CallingConv.td
17319     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17320     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17321                        DAG.getConstant(10, dl, MVT::i64));
17322     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17323                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17324                                 false, false, 0);
17325
17326     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17327                        DAG.getConstant(12, dl, MVT::i64));
17328     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17329                                 MachinePointerInfo(TrmpAddr, 12),
17330                                 false, false, 2);
17331
17332     // Jump to the nested function.
17333     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17334     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17335                        DAG.getConstant(20, dl, MVT::i64));
17336     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17337                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17338                                 false, false, 0);
17339
17340     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17341     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17342                        DAG.getConstant(22, dl, MVT::i64));
17343     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17344                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17345                                 false, false, 0);
17346
17347     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17348   } else {
17349     const Function *Func =
17350       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17351     CallingConv::ID CC = Func->getCallingConv();
17352     unsigned NestReg;
17353
17354     switch (CC) {
17355     default:
17356       llvm_unreachable("Unsupported calling convention");
17357     case CallingConv::C:
17358     case CallingConv::X86_StdCall: {
17359       // Pass 'nest' parameter in ECX.
17360       // Must be kept in sync with X86CallingConv.td
17361       NestReg = X86::ECX;
17362
17363       // Check that ECX wasn't needed by an 'inreg' parameter.
17364       FunctionType *FTy = Func->getFunctionType();
17365       const AttributeSet &Attrs = Func->getAttributes();
17366
17367       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17368         unsigned InRegCount = 0;
17369         unsigned Idx = 1;
17370
17371         for (FunctionType::param_iterator I = FTy->param_begin(),
17372              E = FTy->param_end(); I != E; ++I, ++Idx)
17373           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17374             auto &DL = DAG.getDataLayout();
17375             // FIXME: should only count parameters that are lowered to integers.
17376             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17377           }
17378
17379         if (InRegCount > 2) {
17380           report_fatal_error("Nest register in use - reduce number of inreg"
17381                              " parameters!");
17382         }
17383       }
17384       break;
17385     }
17386     case CallingConv::X86_FastCall:
17387     case CallingConv::X86_ThisCall:
17388     case CallingConv::Fast:
17389       // Pass 'nest' parameter in EAX.
17390       // Must be kept in sync with X86CallingConv.td
17391       NestReg = X86::EAX;
17392       break;
17393     }
17394
17395     SDValue OutChains[4];
17396     SDValue Addr, Disp;
17397
17398     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17399                        DAG.getConstant(10, dl, MVT::i32));
17400     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17401
17402     // This is storing the opcode for MOV32ri.
17403     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17404     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17405     OutChains[0] = DAG.getStore(Root, dl,
17406                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17407                                 Trmp, MachinePointerInfo(TrmpAddr),
17408                                 false, false, 0);
17409
17410     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17411                        DAG.getConstant(1, dl, MVT::i32));
17412     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17413                                 MachinePointerInfo(TrmpAddr, 1),
17414                                 false, false, 1);
17415
17416     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17417     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17418                        DAG.getConstant(5, dl, MVT::i32));
17419     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17420                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17421                                 false, false, 1);
17422
17423     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17424                        DAG.getConstant(6, dl, MVT::i32));
17425     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17426                                 MachinePointerInfo(TrmpAddr, 6),
17427                                 false, false, 1);
17428
17429     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17430   }
17431 }
17432
17433 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17434                                             SelectionDAG &DAG) const {
17435   /*
17436    The rounding mode is in bits 11:10 of FPSR, and has the following
17437    settings:
17438      00 Round to nearest
17439      01 Round to -inf
17440      10 Round to +inf
17441      11 Round to 0
17442
17443   FLT_ROUNDS, on the other hand, expects the following:
17444     -1 Undefined
17445      0 Round to 0
17446      1 Round to nearest
17447      2 Round to +inf
17448      3 Round to -inf
17449
17450   To perform the conversion, we do:
17451     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17452   */
17453
17454   MachineFunction &MF = DAG.getMachineFunction();
17455   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17456   unsigned StackAlignment = TFI.getStackAlignment();
17457   MVT VT = Op.getSimpleValueType();
17458   SDLoc DL(Op);
17459
17460   // Save FP Control Word to stack slot
17461   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17462   SDValue StackSlot =
17463       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17464
17465   MachineMemOperand *MMO =
17466       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17467                               MachineMemOperand::MOStore, 2, 2);
17468
17469   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17470   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17471                                           DAG.getVTList(MVT::Other),
17472                                           Ops, MVT::i16, MMO);
17473
17474   // Load FP Control Word from stack slot
17475   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17476                             MachinePointerInfo(), false, false, false, 0);
17477
17478   // Transform as necessary
17479   SDValue CWD1 =
17480     DAG.getNode(ISD::SRL, DL, MVT::i16,
17481                 DAG.getNode(ISD::AND, DL, MVT::i16,
17482                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17483                 DAG.getConstant(11, DL, MVT::i8));
17484   SDValue CWD2 =
17485     DAG.getNode(ISD::SRL, DL, MVT::i16,
17486                 DAG.getNode(ISD::AND, DL, MVT::i16,
17487                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17488                 DAG.getConstant(9, DL, MVT::i8));
17489
17490   SDValue RetVal =
17491     DAG.getNode(ISD::AND, DL, MVT::i16,
17492                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17493                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17494                             DAG.getConstant(1, DL, MVT::i16)),
17495                 DAG.getConstant(3, DL, MVT::i16));
17496
17497   return DAG.getNode((VT.getSizeInBits() < 16 ?
17498                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17499 }
17500
17501 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17502 //
17503 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17504 //    to 512-bit vector.
17505 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17506 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17507 //    split the vector, perform operation on it's Lo a Hi part and
17508 //    concatenate the results.
17509 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17510   SDLoc dl(Op);
17511   MVT VT = Op.getSimpleValueType();
17512   MVT EltVT = VT.getVectorElementType();
17513   unsigned NumElems = VT.getVectorNumElements();
17514
17515   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17516     // Extend to 512 bit vector.
17517     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17518               "Unsupported value type for operation");
17519
17520     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17521     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17522                                  DAG.getUNDEF(NewVT),
17523                                  Op.getOperand(0),
17524                                  DAG.getIntPtrConstant(0, dl));
17525     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17526
17527     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17528                        DAG.getIntPtrConstant(0, dl));
17529   }
17530
17531   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17532           "Unsupported element type");
17533
17534   if (16 < NumElems) {
17535     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17536     SDValue Lo, Hi;
17537     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17538     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17539
17540     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17541     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17542
17543     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17544   }
17545
17546   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17547
17548   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17549           "Unsupported value type for operation");
17550
17551   // Use native supported vector instruction vplzcntd.
17552   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17553   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17554   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17555   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17556
17557   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17558 }
17559
17560 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17561                          SelectionDAG &DAG) {
17562   MVT VT = Op.getSimpleValueType();
17563   EVT OpVT = VT;
17564   unsigned NumBits = VT.getSizeInBits();
17565   SDLoc dl(Op);
17566
17567   if (VT.isVector() && Subtarget->hasAVX512())
17568     return LowerVectorCTLZ_AVX512(Op, DAG);
17569
17570   Op = Op.getOperand(0);
17571   if (VT == MVT::i8) {
17572     // Zero extend to i32 since there is not an i8 bsr.
17573     OpVT = MVT::i32;
17574     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17575   }
17576
17577   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17578   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17579   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17580
17581   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17582   SDValue Ops[] = {
17583     Op,
17584     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17585     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17586     Op.getValue(1)
17587   };
17588   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17589
17590   // Finally xor with NumBits-1.
17591   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17592                    DAG.getConstant(NumBits - 1, dl, OpVT));
17593
17594   if (VT == MVT::i8)
17595     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17596   return Op;
17597 }
17598
17599 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17600                                     SelectionDAG &DAG) {
17601   MVT VT = Op.getSimpleValueType();
17602   EVT OpVT = VT;
17603   unsigned NumBits = VT.getSizeInBits();
17604   SDLoc dl(Op);
17605
17606   if (VT.isVector() && Subtarget->hasAVX512())
17607     return LowerVectorCTLZ_AVX512(Op, DAG);
17608
17609   Op = Op.getOperand(0);
17610   if (VT == MVT::i8) {
17611     // Zero extend to i32 since there is not an i8 bsr.
17612     OpVT = MVT::i32;
17613     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17614   }
17615
17616   // Issue a bsr (scan bits in reverse).
17617   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17618   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17619
17620   // And xor with NumBits-1.
17621   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17622                    DAG.getConstant(NumBits - 1, dl, OpVT));
17623
17624   if (VT == MVT::i8)
17625     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17626   return Op;
17627 }
17628
17629 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17630   MVT VT = Op.getSimpleValueType();
17631   unsigned NumBits = VT.getScalarSizeInBits();
17632   SDLoc dl(Op);
17633
17634   if (VT.isVector()) {
17635     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17636
17637     SDValue N0 = Op.getOperand(0);
17638     SDValue Zero = DAG.getConstant(0, dl, VT);
17639
17640     // lsb(x) = (x & -x)
17641     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17642                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17643
17644     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17645     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17646         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17647       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17648       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17649                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17650     }
17651
17652     // cttz(x) = ctpop(lsb - 1)
17653     SDValue One = DAG.getConstant(1, dl, VT);
17654     return DAG.getNode(ISD::CTPOP, dl, VT,
17655                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17656   }
17657
17658   assert(Op.getOpcode() == ISD::CTTZ &&
17659          "Only scalar CTTZ requires custom lowering");
17660
17661   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17662   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17663   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17664
17665   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17666   SDValue Ops[] = {
17667     Op,
17668     DAG.getConstant(NumBits, dl, VT),
17669     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17670     Op.getValue(1)
17671   };
17672   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17673 }
17674
17675 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17676 // ones, and then concatenate the result back.
17677 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17678   MVT VT = Op.getSimpleValueType();
17679
17680   assert(VT.is256BitVector() && VT.isInteger() &&
17681          "Unsupported value type for operation");
17682
17683   unsigned NumElems = VT.getVectorNumElements();
17684   SDLoc dl(Op);
17685
17686   // Extract the LHS vectors
17687   SDValue LHS = Op.getOperand(0);
17688   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17689   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17690
17691   // Extract the RHS vectors
17692   SDValue RHS = Op.getOperand(1);
17693   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17694   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17695
17696   MVT EltVT = VT.getVectorElementType();
17697   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17698
17699   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17700                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17701                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17702 }
17703
17704 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17705   if (Op.getValueType() == MVT::i1)
17706     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17707                        Op.getOperand(0), Op.getOperand(1));
17708   assert(Op.getSimpleValueType().is256BitVector() &&
17709          Op.getSimpleValueType().isInteger() &&
17710          "Only handle AVX 256-bit vector integer operation");
17711   return Lower256IntArith(Op, DAG);
17712 }
17713
17714 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17715   if (Op.getValueType() == MVT::i1)
17716     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17717                        Op.getOperand(0), Op.getOperand(1));
17718   assert(Op.getSimpleValueType().is256BitVector() &&
17719          Op.getSimpleValueType().isInteger() &&
17720          "Only handle AVX 256-bit vector integer operation");
17721   return Lower256IntArith(Op, DAG);
17722 }
17723
17724 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17725   assert(Op.getSimpleValueType().is256BitVector() &&
17726          Op.getSimpleValueType().isInteger() &&
17727          "Only handle AVX 256-bit vector integer operation");
17728   return Lower256IntArith(Op, DAG);
17729 }
17730
17731 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17732                         SelectionDAG &DAG) {
17733   SDLoc dl(Op);
17734   MVT VT = Op.getSimpleValueType();
17735
17736   if (VT == MVT::i1)
17737     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17738
17739   // Decompose 256-bit ops into smaller 128-bit ops.
17740   if (VT.is256BitVector() && !Subtarget->hasInt256())
17741     return Lower256IntArith(Op, DAG);
17742
17743   SDValue A = Op.getOperand(0);
17744   SDValue B = Op.getOperand(1);
17745
17746   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17747   // pairs, multiply and truncate.
17748   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17749     if (Subtarget->hasInt256()) {
17750       if (VT == MVT::v32i8) {
17751         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17752         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17753         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17754         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17755         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17756         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17757         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17758         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17759                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17760                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17761       }
17762
17763       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17764       return DAG.getNode(
17765           ISD::TRUNCATE, dl, VT,
17766           DAG.getNode(ISD::MUL, dl, ExVT,
17767                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17768                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17769     }
17770
17771     assert(VT == MVT::v16i8 &&
17772            "Pre-AVX2 support only supports v16i8 multiplication");
17773     MVT ExVT = MVT::v8i16;
17774
17775     // Extract the lo parts and sign extend to i16
17776     SDValue ALo, BLo;
17777     if (Subtarget->hasSSE41()) {
17778       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17779       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17780     } else {
17781       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17782                               -1, 4, -1, 5, -1, 6, -1, 7};
17783       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17784       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17785       ALo = DAG.getBitcast(ExVT, ALo);
17786       BLo = DAG.getBitcast(ExVT, BLo);
17787       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17788       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17789     }
17790
17791     // Extract the hi parts and sign extend to i16
17792     SDValue AHi, BHi;
17793     if (Subtarget->hasSSE41()) {
17794       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17795                               -1, -1, -1, -1, -1, -1, -1, -1};
17796       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17797       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17798       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17799       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17800     } else {
17801       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17802                               -1, 12, -1, 13, -1, 14, -1, 15};
17803       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17804       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17805       AHi = DAG.getBitcast(ExVT, AHi);
17806       BHi = DAG.getBitcast(ExVT, BHi);
17807       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17808       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17809     }
17810
17811     // Multiply, mask the lower 8bits of the lo/hi results and pack
17812     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17813     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17814     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17815     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17816     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17817   }
17818
17819   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17820   if (VT == MVT::v4i32) {
17821     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17822            "Should not custom lower when pmuldq is available!");
17823
17824     // Extract the odd parts.
17825     static const int UnpackMask[] = { 1, -1, 3, -1 };
17826     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17827     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17828
17829     // Multiply the even parts.
17830     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17831     // Now multiply odd parts.
17832     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17833
17834     Evens = DAG.getBitcast(VT, Evens);
17835     Odds = DAG.getBitcast(VT, Odds);
17836
17837     // Merge the two vectors back together with a shuffle. This expands into 2
17838     // shuffles.
17839     static const int ShufMask[] = { 0, 4, 2, 6 };
17840     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17841   }
17842
17843   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17844          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17845
17846   //  Ahi = psrlqi(a, 32);
17847   //  Bhi = psrlqi(b, 32);
17848   //
17849   //  AloBlo = pmuludq(a, b);
17850   //  AloBhi = pmuludq(a, Bhi);
17851   //  AhiBlo = pmuludq(Ahi, b);
17852
17853   //  AloBhi = psllqi(AloBhi, 32);
17854   //  AhiBlo = psllqi(AhiBlo, 32);
17855   //  return AloBlo + AloBhi + AhiBlo;
17856
17857   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17858   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17859
17860   SDValue AhiBlo = Ahi;
17861   SDValue AloBhi = Bhi;
17862   // Bit cast to 32-bit vectors for MULUDQ
17863   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17864                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17865   A = DAG.getBitcast(MulVT, A);
17866   B = DAG.getBitcast(MulVT, B);
17867   Ahi = DAG.getBitcast(MulVT, Ahi);
17868   Bhi = DAG.getBitcast(MulVT, Bhi);
17869
17870   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17871   // After shifting right const values the result may be all-zero.
17872   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17873     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17874     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17875   }
17876   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17877     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17878     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17879   }
17880
17881   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17882   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17883 }
17884
17885 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17886   assert(Subtarget->isTargetWin64() && "Unexpected target");
17887   EVT VT = Op.getValueType();
17888   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17889          "Unexpected return type for lowering");
17890
17891   RTLIB::Libcall LC;
17892   bool isSigned;
17893   switch (Op->getOpcode()) {
17894   default: llvm_unreachable("Unexpected request for libcall!");
17895   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17896   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17897   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17898   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17899   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17900   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17901   }
17902
17903   SDLoc dl(Op);
17904   SDValue InChain = DAG.getEntryNode();
17905
17906   TargetLowering::ArgListTy Args;
17907   TargetLowering::ArgListEntry Entry;
17908   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17909     EVT ArgVT = Op->getOperand(i).getValueType();
17910     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17911            "Unexpected argument type for lowering");
17912     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17913     Entry.Node = StackPtr;
17914     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17915                            false, false, 16);
17916     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17917     Entry.Ty = PointerType::get(ArgTy,0);
17918     Entry.isSExt = false;
17919     Entry.isZExt = false;
17920     Args.push_back(Entry);
17921   }
17922
17923   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17924                                          getPointerTy(DAG.getDataLayout()));
17925
17926   TargetLowering::CallLoweringInfo CLI(DAG);
17927   CLI.setDebugLoc(dl).setChain(InChain)
17928     .setCallee(getLibcallCallingConv(LC),
17929                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17930                Callee, std::move(Args), 0)
17931     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17932
17933   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17934   return DAG.getBitcast(VT, CallInfo.first);
17935 }
17936
17937 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17938                              SelectionDAG &DAG) {
17939   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17940   EVT VT = Op0.getValueType();
17941   SDLoc dl(Op);
17942
17943   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17944          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17945
17946   // PMULxD operations multiply each even value (starting at 0) of LHS with
17947   // the related value of RHS and produce a widen result.
17948   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17949   // => <2 x i64> <ae|cg>
17950   //
17951   // In other word, to have all the results, we need to perform two PMULxD:
17952   // 1. one with the even values.
17953   // 2. one with the odd values.
17954   // To achieve #2, with need to place the odd values at an even position.
17955   //
17956   // Place the odd value at an even position (basically, shift all values 1
17957   // step to the left):
17958   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17959   // <a|b|c|d> => <b|undef|d|undef>
17960   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17961   // <e|f|g|h> => <f|undef|h|undef>
17962   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17963
17964   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17965   // ints.
17966   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17967   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17968   unsigned Opcode =
17969       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17970   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17971   // => <2 x i64> <ae|cg>
17972   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17973   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17974   // => <2 x i64> <bf|dh>
17975   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17976
17977   // Shuffle it back into the right order.
17978   SDValue Highs, Lows;
17979   if (VT == MVT::v8i32) {
17980     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17981     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17982     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17983     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17984   } else {
17985     const int HighMask[] = {1, 5, 3, 7};
17986     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17987     const int LowMask[] = {0, 4, 2, 6};
17988     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17989   }
17990
17991   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17992   // unsigned multiply.
17993   if (IsSigned && !Subtarget->hasSSE41()) {
17994     SDValue ShAmt = DAG.getConstant(
17995         31, dl,
17996         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17997     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17998                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17999     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18000                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18001
18002     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18003     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18004   }
18005
18006   // The first result of MUL_LOHI is actually the low value, followed by the
18007   // high value.
18008   SDValue Ops[] = {Lows, Highs};
18009   return DAG.getMergeValues(Ops, dl);
18010 }
18011
18012 // Return true if the required (according to Opcode) shift-imm form is natively
18013 // supported by the Subtarget
18014 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18015                                         unsigned Opcode) {
18016   if (VT.getScalarSizeInBits() < 16)
18017     return false;
18018
18019   if (VT.is512BitVector() &&
18020       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18021     return true;
18022
18023   bool LShift = VT.is128BitVector() ||
18024     (VT.is256BitVector() && Subtarget->hasInt256());
18025
18026   bool AShift = LShift && (Subtarget->hasVLX() ||
18027     (VT != MVT::v2i64 && VT != MVT::v4i64));
18028   return (Opcode == ISD::SRA) ? AShift : LShift;
18029 }
18030
18031 // The shift amount is a variable, but it is the same for all vector lanes.
18032 // These instructions are defined together with shift-immediate.
18033 static
18034 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18035                                       unsigned Opcode) {
18036   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18037 }
18038
18039 // Return true if the required (according to Opcode) variable-shift form is
18040 // natively supported by the Subtarget
18041 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18042                                     unsigned Opcode) {
18043
18044   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18045     return false;
18046
18047   // vXi16 supported only on AVX-512, BWI
18048   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18049     return false;
18050
18051   if (VT.is512BitVector() || Subtarget->hasVLX())
18052     return true;
18053
18054   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18055   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18056   return (Opcode == ISD::SRA) ? AShift : LShift;
18057 }
18058
18059 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18060                                          const X86Subtarget *Subtarget) {
18061   MVT VT = Op.getSimpleValueType();
18062   SDLoc dl(Op);
18063   SDValue R = Op.getOperand(0);
18064   SDValue Amt = Op.getOperand(1);
18065
18066   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18067     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18068
18069   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18070     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18071     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18072     SDValue Ex = DAG.getBitcast(ExVT, R);
18073
18074     if (ShiftAmt >= 32) {
18075       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18076       SDValue Upper =
18077           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18078       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18079                                                  ShiftAmt - 32, DAG);
18080       if (VT == MVT::v2i64)
18081         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18082       if (VT == MVT::v4i64)
18083         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18084                                   {9, 1, 11, 3, 13, 5, 15, 7});
18085     } else {
18086       // SRA upper i32, SHL whole i64 and select lower i32.
18087       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18088                                                  ShiftAmt, DAG);
18089       SDValue Lower =
18090           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18091       Lower = DAG.getBitcast(ExVT, Lower);
18092       if (VT == MVT::v2i64)
18093         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18094       if (VT == MVT::v4i64)
18095         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18096                                   {8, 1, 10, 3, 12, 5, 14, 7});
18097     }
18098     return DAG.getBitcast(VT, Ex);
18099   };
18100
18101   // Optimize shl/srl/sra with constant shift amount.
18102   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18103     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18104       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18105
18106       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18107         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18108
18109       // i64 SRA needs to be performed as partial shifts.
18110       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18111           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18112         return ArithmeticShiftRight64(ShiftAmt);
18113
18114       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18115         unsigned NumElts = VT.getVectorNumElements();
18116         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18117
18118         // Simple i8 add case
18119         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18120           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18121
18122         // ashr(R, 7)  === cmp_slt(R, 0)
18123         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18124           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18125           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18126         }
18127
18128         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18129         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18130           return SDValue();
18131
18132         if (Op.getOpcode() == ISD::SHL) {
18133           // Make a large shift.
18134           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18135                                                    R, ShiftAmt, DAG);
18136           SHL = DAG.getBitcast(VT, SHL);
18137           // Zero out the rightmost bits.
18138           SmallVector<SDValue, 32> V(
18139               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18140           return DAG.getNode(ISD::AND, dl, VT, SHL,
18141                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18142         }
18143         if (Op.getOpcode() == ISD::SRL) {
18144           // Make a large shift.
18145           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18146                                                    R, ShiftAmt, DAG);
18147           SRL = DAG.getBitcast(VT, SRL);
18148           // Zero out the leftmost bits.
18149           SmallVector<SDValue, 32> V(
18150               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18151           return DAG.getNode(ISD::AND, dl, VT, SRL,
18152                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18153         }
18154         if (Op.getOpcode() == ISD::SRA) {
18155           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18156           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18157           SmallVector<SDValue, 32> V(NumElts,
18158                                      DAG.getConstant(128 >> ShiftAmt, dl,
18159                                                      MVT::i8));
18160           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18161           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18162           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18163           return Res;
18164         }
18165         llvm_unreachable("Unknown shift opcode.");
18166       }
18167     }
18168   }
18169
18170   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18171   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18172       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18173
18174     // Peek through any splat that was introduced for i64 shift vectorization.
18175     int SplatIndex = -1;
18176     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18177       if (SVN->isSplat()) {
18178         SplatIndex = SVN->getSplatIndex();
18179         Amt = Amt.getOperand(0);
18180         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18181                "Splat shuffle referencing second operand");
18182       }
18183
18184     if (Amt.getOpcode() != ISD::BITCAST ||
18185         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18186       return SDValue();
18187
18188     Amt = Amt.getOperand(0);
18189     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18190                      VT.getVectorNumElements();
18191     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18192     uint64_t ShiftAmt = 0;
18193     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18194     for (unsigned i = 0; i != Ratio; ++i) {
18195       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18196       if (!C)
18197         return SDValue();
18198       // 6 == Log2(64)
18199       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18200     }
18201
18202     // Check remaining shift amounts (if not a splat).
18203     if (SplatIndex < 0) {
18204       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18205         uint64_t ShAmt = 0;
18206         for (unsigned j = 0; j != Ratio; ++j) {
18207           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18208           if (!C)
18209             return SDValue();
18210           // 6 == Log2(64)
18211           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18212         }
18213         if (ShAmt != ShiftAmt)
18214           return SDValue();
18215       }
18216     }
18217
18218     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18219       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18220
18221     if (Op.getOpcode() == ISD::SRA)
18222       return ArithmeticShiftRight64(ShiftAmt);
18223   }
18224
18225   return SDValue();
18226 }
18227
18228 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18229                                         const X86Subtarget* Subtarget) {
18230   MVT VT = Op.getSimpleValueType();
18231   SDLoc dl(Op);
18232   SDValue R = Op.getOperand(0);
18233   SDValue Amt = Op.getOperand(1);
18234
18235   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18236     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18237
18238   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18239     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18240
18241   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18242     SDValue BaseShAmt;
18243     EVT EltVT = VT.getVectorElementType();
18244
18245     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18246       // Check if this build_vector node is doing a splat.
18247       // If so, then set BaseShAmt equal to the splat value.
18248       BaseShAmt = BV->getSplatValue();
18249       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18250         BaseShAmt = SDValue();
18251     } else {
18252       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18253         Amt = Amt.getOperand(0);
18254
18255       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18256       if (SVN && SVN->isSplat()) {
18257         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18258         SDValue InVec = Amt.getOperand(0);
18259         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18260           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18261                  "Unexpected shuffle index found!");
18262           BaseShAmt = InVec.getOperand(SplatIdx);
18263         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18264            if (ConstantSDNode *C =
18265                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18266              if (C->getZExtValue() == SplatIdx)
18267                BaseShAmt = InVec.getOperand(1);
18268            }
18269         }
18270
18271         if (!BaseShAmt)
18272           // Avoid introducing an extract element from a shuffle.
18273           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18274                                   DAG.getIntPtrConstant(SplatIdx, dl));
18275       }
18276     }
18277
18278     if (BaseShAmt.getNode()) {
18279       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18280       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18281         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18282       else if (EltVT.bitsLT(MVT::i32))
18283         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18284
18285       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18286     }
18287   }
18288
18289   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18290   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18291       Amt.getOpcode() == ISD::BITCAST &&
18292       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18293     Amt = Amt.getOperand(0);
18294     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18295                      VT.getVectorNumElements();
18296     std::vector<SDValue> Vals(Ratio);
18297     for (unsigned i = 0; i != Ratio; ++i)
18298       Vals[i] = Amt.getOperand(i);
18299     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18300       for (unsigned j = 0; j != Ratio; ++j)
18301         if (Vals[j] != Amt.getOperand(i + j))
18302           return SDValue();
18303     }
18304
18305     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18306       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18307   }
18308   return SDValue();
18309 }
18310
18311 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18312                           SelectionDAG &DAG) {
18313   MVT VT = Op.getSimpleValueType();
18314   SDLoc dl(Op);
18315   SDValue R = Op.getOperand(0);
18316   SDValue Amt = Op.getOperand(1);
18317
18318   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18319   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18320
18321   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18322     return V;
18323
18324   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18325     return V;
18326
18327   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18328     return Op;
18329
18330   // XOP has 128-bit variable logical/arithmetic shifts.
18331   // +ve/-ve Amt = shift left/right.
18332   if (Subtarget->hasXOP() &&
18333       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18334        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18335     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18336       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18337       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18338     }
18339     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18340       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18341     if (Op.getOpcode() == ISD::SRA)
18342       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18343   }
18344
18345   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18346   // shifts per-lane and then shuffle the partial results back together.
18347   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18348     // Splat the shift amounts so the scalar shifts above will catch it.
18349     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18350     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18351     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18352     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18353     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18354   }
18355
18356   // i64 vector arithmetic shift can be emulated with the transform:
18357   // M = lshr(SIGN_BIT, Amt)
18358   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18359   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18360       Op.getOpcode() == ISD::SRA) {
18361     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18362     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18363     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18364     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18365     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18366     return R;
18367   }
18368
18369   // If possible, lower this packed shift into a vector multiply instead of
18370   // expanding it into a sequence of scalar shifts.
18371   // Do this only if the vector shift count is a constant build_vector.
18372   if (Op.getOpcode() == ISD::SHL &&
18373       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18374        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18375       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18376     SmallVector<SDValue, 8> Elts;
18377     EVT SVT = VT.getScalarType();
18378     unsigned SVTBits = SVT.getSizeInBits();
18379     const APInt &One = APInt(SVTBits, 1);
18380     unsigned NumElems = VT.getVectorNumElements();
18381
18382     for (unsigned i=0; i !=NumElems; ++i) {
18383       SDValue Op = Amt->getOperand(i);
18384       if (Op->getOpcode() == ISD::UNDEF) {
18385         Elts.push_back(Op);
18386         continue;
18387       }
18388
18389       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18390       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18391       uint64_t ShAmt = C.getZExtValue();
18392       if (ShAmt >= SVTBits) {
18393         Elts.push_back(DAG.getUNDEF(SVT));
18394         continue;
18395       }
18396       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18397     }
18398     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18399     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18400   }
18401
18402   // Lower SHL with variable shift amount.
18403   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18404     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18405
18406     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18407                      DAG.getConstant(0x3f800000U, dl, VT));
18408     Op = DAG.getBitcast(MVT::v4f32, Op);
18409     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18410     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18411   }
18412
18413   // If possible, lower this shift as a sequence of two shifts by
18414   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18415   // Example:
18416   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18417   //
18418   // Could be rewritten as:
18419   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18420   //
18421   // The advantage is that the two shifts from the example would be
18422   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18423   // the vector shift into four scalar shifts plus four pairs of vector
18424   // insert/extract.
18425   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18426       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18427     unsigned TargetOpcode = X86ISD::MOVSS;
18428     bool CanBeSimplified;
18429     // The splat value for the first packed shift (the 'X' from the example).
18430     SDValue Amt1 = Amt->getOperand(0);
18431     // The splat value for the second packed shift (the 'Y' from the example).
18432     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18433                                         Amt->getOperand(2);
18434
18435     // See if it is possible to replace this node with a sequence of
18436     // two shifts followed by a MOVSS/MOVSD
18437     if (VT == MVT::v4i32) {
18438       // Check if it is legal to use a MOVSS.
18439       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18440                         Amt2 == Amt->getOperand(3);
18441       if (!CanBeSimplified) {
18442         // Otherwise, check if we can still simplify this node using a MOVSD.
18443         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18444                           Amt->getOperand(2) == Amt->getOperand(3);
18445         TargetOpcode = X86ISD::MOVSD;
18446         Amt2 = Amt->getOperand(2);
18447       }
18448     } else {
18449       // Do similar checks for the case where the machine value type
18450       // is MVT::v8i16.
18451       CanBeSimplified = Amt1 == Amt->getOperand(1);
18452       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18453         CanBeSimplified = Amt2 == Amt->getOperand(i);
18454
18455       if (!CanBeSimplified) {
18456         TargetOpcode = X86ISD::MOVSD;
18457         CanBeSimplified = true;
18458         Amt2 = Amt->getOperand(4);
18459         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18460           CanBeSimplified = Amt1 == Amt->getOperand(i);
18461         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18462           CanBeSimplified = Amt2 == Amt->getOperand(j);
18463       }
18464     }
18465
18466     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18467         isa<ConstantSDNode>(Amt2)) {
18468       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18469       EVT CastVT = MVT::v4i32;
18470       SDValue Splat1 =
18471         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18472       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18473       SDValue Splat2 =
18474         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18475       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18476       if (TargetOpcode == X86ISD::MOVSD)
18477         CastVT = MVT::v2i64;
18478       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18479       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18480       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18481                                             BitCast1, DAG);
18482       return DAG.getBitcast(VT, Result);
18483     }
18484   }
18485
18486   // v4i32 Non Uniform Shifts.
18487   // If the shift amount is constant we can shift each lane using the SSE2
18488   // immediate shifts, else we need to zero-extend each lane to the lower i64
18489   // and shift using the SSE2 variable shifts.
18490   // The separate results can then be blended together.
18491   if (VT == MVT::v4i32) {
18492     unsigned Opc = Op.getOpcode();
18493     SDValue Amt0, Amt1, Amt2, Amt3;
18494     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18495       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18496       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18497       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18498       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18499     } else {
18500       // ISD::SHL is handled above but we include it here for completeness.
18501       switch (Opc) {
18502       default:
18503         llvm_unreachable("Unknown target vector shift node");
18504       case ISD::SHL:
18505         Opc = X86ISD::VSHL;
18506         break;
18507       case ISD::SRL:
18508         Opc = X86ISD::VSRL;
18509         break;
18510       case ISD::SRA:
18511         Opc = X86ISD::VSRA;
18512         break;
18513       }
18514       // The SSE2 shifts use the lower i64 as the same shift amount for
18515       // all lanes and the upper i64 is ignored. These shuffle masks
18516       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18517       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18518       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18519       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18520       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18521       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18522     }
18523
18524     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18525     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18526     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18527     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18528     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18529     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18530     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18531   }
18532
18533   if (VT == MVT::v16i8 ||
18534       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18535     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18536     unsigned ShiftOpcode = Op->getOpcode();
18537
18538     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18539       // On SSE41 targets we make use of the fact that VSELECT lowers
18540       // to PBLENDVB which selects bytes based just on the sign bit.
18541       if (Subtarget->hasSSE41()) {
18542         V0 = DAG.getBitcast(VT, V0);
18543         V1 = DAG.getBitcast(VT, V1);
18544         Sel = DAG.getBitcast(VT, Sel);
18545         return DAG.getBitcast(SelVT,
18546                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18547       }
18548       // On pre-SSE41 targets we test for the sign bit by comparing to
18549       // zero - a negative value will set all bits of the lanes to true
18550       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18551       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18552       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18553       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18554     };
18555
18556     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18557     // We can safely do this using i16 shifts as we're only interested in
18558     // the 3 lower bits of each byte.
18559     Amt = DAG.getBitcast(ExtVT, Amt);
18560     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18561     Amt = DAG.getBitcast(VT, Amt);
18562
18563     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18564       // r = VSELECT(r, shift(r, 4), a);
18565       SDValue M =
18566           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18567       R = SignBitSelect(VT, Amt, M, R);
18568
18569       // a += a
18570       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18571
18572       // r = VSELECT(r, shift(r, 2), a);
18573       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18574       R = SignBitSelect(VT, Amt, M, R);
18575
18576       // a += a
18577       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18578
18579       // return VSELECT(r, shift(r, 1), a);
18580       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18581       R = SignBitSelect(VT, Amt, M, R);
18582       return R;
18583     }
18584
18585     if (Op->getOpcode() == ISD::SRA) {
18586       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18587       // so we can correctly sign extend. We don't care what happens to the
18588       // lower byte.
18589       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18590       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18591       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18592       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18593       ALo = DAG.getBitcast(ExtVT, ALo);
18594       AHi = DAG.getBitcast(ExtVT, AHi);
18595       RLo = DAG.getBitcast(ExtVT, RLo);
18596       RHi = DAG.getBitcast(ExtVT, RHi);
18597
18598       // r = VSELECT(r, shift(r, 4), a);
18599       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18600                                 DAG.getConstant(4, dl, ExtVT));
18601       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18602                                 DAG.getConstant(4, dl, ExtVT));
18603       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18604       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18605
18606       // a += a
18607       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18608       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18609
18610       // r = VSELECT(r, shift(r, 2), a);
18611       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18612                         DAG.getConstant(2, dl, ExtVT));
18613       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18614                         DAG.getConstant(2, dl, ExtVT));
18615       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18616       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18617
18618       // a += a
18619       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18620       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18621
18622       // r = VSELECT(r, shift(r, 1), a);
18623       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18624                         DAG.getConstant(1, dl, ExtVT));
18625       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18626                         DAG.getConstant(1, dl, ExtVT));
18627       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18628       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18629
18630       // Logical shift the result back to the lower byte, leaving a zero upper
18631       // byte
18632       // meaning that we can safely pack with PACKUSWB.
18633       RLo =
18634           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18635       RHi =
18636           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18637       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18638     }
18639   }
18640
18641   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18642   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18643   // solution better.
18644   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18645     MVT ExtVT = MVT::v8i32;
18646     unsigned ExtOpc =
18647         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18648     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18649     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18650     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18651                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18652   }
18653
18654   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18655     MVT ExtVT = MVT::v8i32;
18656     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18657     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18658     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18659     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18660     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18661     ALo = DAG.getBitcast(ExtVT, ALo);
18662     AHi = DAG.getBitcast(ExtVT, AHi);
18663     RLo = DAG.getBitcast(ExtVT, RLo);
18664     RHi = DAG.getBitcast(ExtVT, RHi);
18665     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18666     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18667     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18668     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18669     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18670   }
18671
18672   if (VT == MVT::v8i16) {
18673     unsigned ShiftOpcode = Op->getOpcode();
18674
18675     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18676       // On SSE41 targets we make use of the fact that VSELECT lowers
18677       // to PBLENDVB which selects bytes based just on the sign bit.
18678       if (Subtarget->hasSSE41()) {
18679         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18680         V0 = DAG.getBitcast(ExtVT, V0);
18681         V1 = DAG.getBitcast(ExtVT, V1);
18682         Sel = DAG.getBitcast(ExtVT, Sel);
18683         return DAG.getBitcast(
18684             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18685       }
18686       // On pre-SSE41 targets we splat the sign bit - a negative value will
18687       // set all bits of the lanes to true and VSELECT uses that in
18688       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18689       SDValue C =
18690           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18691       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18692     };
18693
18694     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18695     if (Subtarget->hasSSE41()) {
18696       // On SSE41 targets we need to replicate the shift mask in both
18697       // bytes for PBLENDVB.
18698       Amt = DAG.getNode(
18699           ISD::OR, dl, VT,
18700           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18701           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18702     } else {
18703       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18704     }
18705
18706     // r = VSELECT(r, shift(r, 8), a);
18707     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18708     R = SignBitSelect(Amt, M, R);
18709
18710     // a += a
18711     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18712
18713     // r = VSELECT(r, shift(r, 4), a);
18714     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18715     R = SignBitSelect(Amt, M, R);
18716
18717     // a += a
18718     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18719
18720     // r = VSELECT(r, shift(r, 2), a);
18721     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18722     R = SignBitSelect(Amt, M, R);
18723
18724     // a += a
18725     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18726
18727     // return VSELECT(r, shift(r, 1), a);
18728     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18729     R = SignBitSelect(Amt, M, R);
18730     return R;
18731   }
18732
18733   // Decompose 256-bit shifts into smaller 128-bit shifts.
18734   if (VT.is256BitVector()) {
18735     unsigned NumElems = VT.getVectorNumElements();
18736     MVT EltVT = VT.getVectorElementType();
18737     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18738
18739     // Extract the two vectors
18740     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18741     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18742
18743     // Recreate the shift amount vectors
18744     SDValue Amt1, Amt2;
18745     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18746       // Constant shift amount
18747       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18748       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18749       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18750
18751       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18752       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18753     } else {
18754       // Variable shift amount
18755       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18756       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18757     }
18758
18759     // Issue new vector shifts for the smaller types
18760     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18761     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18762
18763     // Concatenate the result back
18764     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18765   }
18766
18767   return SDValue();
18768 }
18769
18770 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
18771                            SelectionDAG &DAG) {
18772   MVT VT = Op.getSimpleValueType();
18773   SDLoc DL(Op);
18774   SDValue R = Op.getOperand(0);
18775   SDValue Amt = Op.getOperand(1);
18776
18777   assert(VT.isVector() && "Custom lowering only for vector rotates!");
18778   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
18779   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
18780
18781   // XOP has 128-bit vector variable + immediate rotates.
18782   // +ve/-ve Amt = rotate left/right.
18783
18784   // Split 256-bit integers.
18785   if (VT.getSizeInBits() == 256)
18786     return Lower256IntArith(Op, DAG);
18787
18788   assert(VT.getSizeInBits() == 128 && "Only rotate 128-bit vectors!");
18789
18790   // Attempt to rotate by immediate.
18791   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18792     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
18793       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
18794       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
18795       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
18796                          DAG.getConstant(RotateAmt, DL, MVT::i8));
18797     }
18798   }
18799
18800   // Use general rotate by variable (per-element).
18801   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
18802 }
18803
18804 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18805   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18806   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18807   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18808   // has only one use.
18809   SDNode *N = Op.getNode();
18810   SDValue LHS = N->getOperand(0);
18811   SDValue RHS = N->getOperand(1);
18812   unsigned BaseOp = 0;
18813   unsigned Cond = 0;
18814   SDLoc DL(Op);
18815   switch (Op.getOpcode()) {
18816   default: llvm_unreachable("Unknown ovf instruction!");
18817   case ISD::SADDO:
18818     // A subtract of one will be selected as a INC. Note that INC doesn't
18819     // set CF, so we can't do this for UADDO.
18820     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18821       if (C->isOne()) {
18822         BaseOp = X86ISD::INC;
18823         Cond = X86::COND_O;
18824         break;
18825       }
18826     BaseOp = X86ISD::ADD;
18827     Cond = X86::COND_O;
18828     break;
18829   case ISD::UADDO:
18830     BaseOp = X86ISD::ADD;
18831     Cond = X86::COND_B;
18832     break;
18833   case ISD::SSUBO:
18834     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18835     // set CF, so we can't do this for USUBO.
18836     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18837       if (C->isOne()) {
18838         BaseOp = X86ISD::DEC;
18839         Cond = X86::COND_O;
18840         break;
18841       }
18842     BaseOp = X86ISD::SUB;
18843     Cond = X86::COND_O;
18844     break;
18845   case ISD::USUBO:
18846     BaseOp = X86ISD::SUB;
18847     Cond = X86::COND_B;
18848     break;
18849   case ISD::SMULO:
18850     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18851     Cond = X86::COND_O;
18852     break;
18853   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18854     if (N->getValueType(0) == MVT::i8) {
18855       BaseOp = X86ISD::UMUL8;
18856       Cond = X86::COND_O;
18857       break;
18858     }
18859     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18860                                  MVT::i32);
18861     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18862
18863     SDValue SetCC =
18864       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18865                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18866                   SDValue(Sum.getNode(), 2));
18867
18868     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18869   }
18870   }
18871
18872   // Also sets EFLAGS.
18873   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18874   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18875
18876   SDValue SetCC =
18877     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18878                 DAG.getConstant(Cond, DL, MVT::i32),
18879                 SDValue(Sum.getNode(), 1));
18880
18881   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18882 }
18883
18884 /// Returns true if the operand type is exactly twice the native width, and
18885 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18886 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18887 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18888 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18889   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18890
18891   if (OpWidth == 64)
18892     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18893   else if (OpWidth == 128)
18894     return Subtarget->hasCmpxchg16b();
18895   else
18896     return false;
18897 }
18898
18899 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18900   return needsCmpXchgNb(SI->getValueOperand()->getType());
18901 }
18902
18903 // Note: this turns large loads into lock cmpxchg8b/16b.
18904 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18905 TargetLowering::AtomicExpansionKind
18906 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18907   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18908   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18909                                                : AtomicExpansionKind::None;
18910 }
18911
18912 TargetLowering::AtomicExpansionKind
18913 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18914   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18915   Type *MemType = AI->getType();
18916
18917   // If the operand is too big, we must see if cmpxchg8/16b is available
18918   // and default to library calls otherwise.
18919   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18920     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18921                                    : AtomicExpansionKind::None;
18922   }
18923
18924   AtomicRMWInst::BinOp Op = AI->getOperation();
18925   switch (Op) {
18926   default:
18927     llvm_unreachable("Unknown atomic operation");
18928   case AtomicRMWInst::Xchg:
18929   case AtomicRMWInst::Add:
18930   case AtomicRMWInst::Sub:
18931     // It's better to use xadd, xsub or xchg for these in all cases.
18932     return AtomicExpansionKind::None;
18933   case AtomicRMWInst::Or:
18934   case AtomicRMWInst::And:
18935   case AtomicRMWInst::Xor:
18936     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18937     // prefix to a normal instruction for these operations.
18938     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18939                             : AtomicExpansionKind::None;
18940   case AtomicRMWInst::Nand:
18941   case AtomicRMWInst::Max:
18942   case AtomicRMWInst::Min:
18943   case AtomicRMWInst::UMax:
18944   case AtomicRMWInst::UMin:
18945     // These always require a non-trivial set of data operations on x86. We must
18946     // use a cmpxchg loop.
18947     return AtomicExpansionKind::CmpXChg;
18948   }
18949 }
18950
18951 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18952   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18953   // no-sse2). There isn't any reason to disable it if the target processor
18954   // supports it.
18955   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18956 }
18957
18958 LoadInst *
18959 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18960   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18961   Type *MemType = AI->getType();
18962   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18963   // there is no benefit in turning such RMWs into loads, and it is actually
18964   // harmful as it introduces a mfence.
18965   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18966     return nullptr;
18967
18968   auto Builder = IRBuilder<>(AI);
18969   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18970   auto SynchScope = AI->getSynchScope();
18971   // We must restrict the ordering to avoid generating loads with Release or
18972   // ReleaseAcquire orderings.
18973   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18974   auto Ptr = AI->getPointerOperand();
18975
18976   // Before the load we need a fence. Here is an example lifted from
18977   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18978   // is required:
18979   // Thread 0:
18980   //   x.store(1, relaxed);
18981   //   r1 = y.fetch_add(0, release);
18982   // Thread 1:
18983   //   y.fetch_add(42, acquire);
18984   //   r2 = x.load(relaxed);
18985   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18986   // lowered to just a load without a fence. A mfence flushes the store buffer,
18987   // making the optimization clearly correct.
18988   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18989   // otherwise, we might be able to be more aggressive on relaxed idempotent
18990   // rmw. In practice, they do not look useful, so we don't try to be
18991   // especially clever.
18992   if (SynchScope == SingleThread)
18993     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18994     // the IR level, so we must wrap it in an intrinsic.
18995     return nullptr;
18996
18997   if (!hasMFENCE(*Subtarget))
18998     // FIXME: it might make sense to use a locked operation here but on a
18999     // different cache-line to prevent cache-line bouncing. In practice it
19000     // is probably a small win, and x86 processors without mfence are rare
19001     // enough that we do not bother.
19002     return nullptr;
19003
19004   Function *MFence =
19005       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19006   Builder.CreateCall(MFence, {});
19007
19008   // Finally we can emit the atomic load.
19009   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19010           AI->getType()->getPrimitiveSizeInBits());
19011   Loaded->setAtomic(Order, SynchScope);
19012   AI->replaceAllUsesWith(Loaded);
19013   AI->eraseFromParent();
19014   return Loaded;
19015 }
19016
19017 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19018                                  SelectionDAG &DAG) {
19019   SDLoc dl(Op);
19020   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19021     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19022   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19023     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19024
19025   // The only fence that needs an instruction is a sequentially-consistent
19026   // cross-thread fence.
19027   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19028     if (hasMFENCE(*Subtarget))
19029       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19030
19031     SDValue Chain = Op.getOperand(0);
19032     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19033     SDValue Ops[] = {
19034       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19035       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19036       DAG.getRegister(0, MVT::i32),            // Index
19037       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19038       DAG.getRegister(0, MVT::i32),            // Segment.
19039       Zero,
19040       Chain
19041     };
19042     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19043     return SDValue(Res, 0);
19044   }
19045
19046   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19047   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19048 }
19049
19050 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19051                              SelectionDAG &DAG) {
19052   MVT T = Op.getSimpleValueType();
19053   SDLoc DL(Op);
19054   unsigned Reg = 0;
19055   unsigned size = 0;
19056   switch(T.SimpleTy) {
19057   default: llvm_unreachable("Invalid value type!");
19058   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19059   case MVT::i16: Reg = X86::AX;  size = 2; break;
19060   case MVT::i32: Reg = X86::EAX; size = 4; break;
19061   case MVT::i64:
19062     assert(Subtarget->is64Bit() && "Node not type legal!");
19063     Reg = X86::RAX; size = 8;
19064     break;
19065   }
19066   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19067                                   Op.getOperand(2), SDValue());
19068   SDValue Ops[] = { cpIn.getValue(0),
19069                     Op.getOperand(1),
19070                     Op.getOperand(3),
19071                     DAG.getTargetConstant(size, DL, MVT::i8),
19072                     cpIn.getValue(1) };
19073   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19074   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19075   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19076                                            Ops, T, MMO);
19077
19078   SDValue cpOut =
19079     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19080   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19081                                       MVT::i32, cpOut.getValue(2));
19082   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19083                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19084                                 EFLAGS);
19085
19086   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19087   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19088   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19089   return SDValue();
19090 }
19091
19092 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19093                             SelectionDAG &DAG) {
19094   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19095   MVT DstVT = Op.getSimpleValueType();
19096
19097   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19098     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19099     if (DstVT != MVT::f64)
19100       // This conversion needs to be expanded.
19101       return SDValue();
19102
19103     SDValue InVec = Op->getOperand(0);
19104     SDLoc dl(Op);
19105     unsigned NumElts = SrcVT.getVectorNumElements();
19106     EVT SVT = SrcVT.getVectorElementType();
19107
19108     // Widen the vector in input in the case of MVT::v2i32.
19109     // Example: from MVT::v2i32 to MVT::v4i32.
19110     SmallVector<SDValue, 16> Elts;
19111     for (unsigned i = 0, e = NumElts; i != e; ++i)
19112       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19113                                  DAG.getIntPtrConstant(i, dl)));
19114
19115     // Explicitly mark the extra elements as Undef.
19116     Elts.append(NumElts, DAG.getUNDEF(SVT));
19117
19118     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19119     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19120     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19121     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19122                        DAG.getIntPtrConstant(0, dl));
19123   }
19124
19125   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19126          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19127   assert((DstVT == MVT::i64 ||
19128           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19129          "Unexpected custom BITCAST");
19130   // i64 <=> MMX conversions are Legal.
19131   if (SrcVT==MVT::i64 && DstVT.isVector())
19132     return Op;
19133   if (DstVT==MVT::i64 && SrcVT.isVector())
19134     return Op;
19135   // MMX <=> MMX conversions are Legal.
19136   if (SrcVT.isVector() && DstVT.isVector())
19137     return Op;
19138   // All other conversions need to be expanded.
19139   return SDValue();
19140 }
19141
19142 /// Compute the horizontal sum of bytes in V for the elements of VT.
19143 ///
19144 /// Requires V to be a byte vector and VT to be an integer vector type with
19145 /// wider elements than V's type. The width of the elements of VT determines
19146 /// how many bytes of V are summed horizontally to produce each element of the
19147 /// result.
19148 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19149                                       const X86Subtarget *Subtarget,
19150                                       SelectionDAG &DAG) {
19151   SDLoc DL(V);
19152   MVT ByteVecVT = V.getSimpleValueType();
19153   MVT EltVT = VT.getVectorElementType();
19154   int NumElts = VT.getVectorNumElements();
19155   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19156          "Expected value to have byte element type.");
19157   assert(EltVT != MVT::i8 &&
19158          "Horizontal byte sum only makes sense for wider elements!");
19159   unsigned VecSize = VT.getSizeInBits();
19160   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19161
19162   // PSADBW instruction horizontally add all bytes and leave the result in i64
19163   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19164   if (EltVT == MVT::i64) {
19165     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19166     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
19167     return DAG.getBitcast(VT, V);
19168   }
19169
19170   if (EltVT == MVT::i32) {
19171     // We unpack the low half and high half into i32s interleaved with zeros so
19172     // that we can use PSADBW to horizontally sum them. The most useful part of
19173     // this is that it lines up the results of two PSADBW instructions to be
19174     // two v2i64 vectors which concatenated are the 4 population counts. We can
19175     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19176     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19177     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19178     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19179
19180     // Do the horizontal sums into two v2i64s.
19181     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19182     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19183                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19184     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
19185                        DAG.getBitcast(ByteVecVT, High), Zeros);
19186
19187     // Merge them together.
19188     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19189     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19190                     DAG.getBitcast(ShortVecVT, Low),
19191                     DAG.getBitcast(ShortVecVT, High));
19192
19193     return DAG.getBitcast(VT, V);
19194   }
19195
19196   // The only element type left is i16.
19197   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19198
19199   // To obtain pop count for each i16 element starting from the pop count for
19200   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19201   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19202   // directly supported.
19203   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19204   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19205   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19206   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19207                   DAG.getBitcast(ByteVecVT, V));
19208   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19209 }
19210
19211 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19212                                         const X86Subtarget *Subtarget,
19213                                         SelectionDAG &DAG) {
19214   MVT VT = Op.getSimpleValueType();
19215   MVT EltVT = VT.getVectorElementType();
19216   unsigned VecSize = VT.getSizeInBits();
19217
19218   // Implement a lookup table in register by using an algorithm based on:
19219   // http://wm.ite.pl/articles/sse-popcount.html
19220   //
19221   // The general idea is that every lower byte nibble in the input vector is an
19222   // index into a in-register pre-computed pop count table. We then split up the
19223   // input vector in two new ones: (1) a vector with only the shifted-right
19224   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19225   // masked out higher ones) for each byte. PSHUB is used separately with both
19226   // to index the in-register table. Next, both are added and the result is a
19227   // i8 vector where each element contains the pop count for input byte.
19228   //
19229   // To obtain the pop count for elements != i8, we follow up with the same
19230   // approach and use additional tricks as described below.
19231   //
19232   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19233                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19234                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19235                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19236
19237   int NumByteElts = VecSize / 8;
19238   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19239   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19240   SmallVector<SDValue, 16> LUTVec;
19241   for (int i = 0; i < NumByteElts; ++i)
19242     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19243   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19244   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19245                                   DAG.getConstant(0x0F, DL, MVT::i8));
19246   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19247
19248   // High nibbles
19249   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19250   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19251   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19252
19253   // Low nibbles
19254   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19255
19256   // The input vector is used as the shuffle mask that index elements into the
19257   // LUT. After counting low and high nibbles, add the vector to obtain the
19258   // final pop count per i8 element.
19259   SDValue HighPopCnt =
19260       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19261   SDValue LowPopCnt =
19262       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19263   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19264
19265   if (EltVT == MVT::i8)
19266     return PopCnt;
19267
19268   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19269 }
19270
19271 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19272                                        const X86Subtarget *Subtarget,
19273                                        SelectionDAG &DAG) {
19274   MVT VT = Op.getSimpleValueType();
19275   assert(VT.is128BitVector() &&
19276          "Only 128-bit vector bitmath lowering supported.");
19277
19278   int VecSize = VT.getSizeInBits();
19279   MVT EltVT = VT.getVectorElementType();
19280   int Len = EltVT.getSizeInBits();
19281
19282   // This is the vectorized version of the "best" algorithm from
19283   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19284   // with a minor tweak to use a series of adds + shifts instead of vector
19285   // multiplications. Implemented for all integer vector types. We only use
19286   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19287   // much faster, even faster than using native popcnt instructions.
19288
19289   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19290     MVT VT = V.getSimpleValueType();
19291     SmallVector<SDValue, 32> Shifters(
19292         VT.getVectorNumElements(),
19293         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19294     return DAG.getNode(OpCode, DL, VT, V,
19295                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19296   };
19297   auto GetMask = [&](SDValue V, APInt Mask) {
19298     MVT VT = V.getSimpleValueType();
19299     SmallVector<SDValue, 32> Masks(
19300         VT.getVectorNumElements(),
19301         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19302     return DAG.getNode(ISD::AND, DL, VT, V,
19303                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19304   };
19305
19306   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19307   // x86, so set the SRL type to have elements at least i16 wide. This is
19308   // correct because all of our SRLs are followed immediately by a mask anyways
19309   // that handles any bits that sneak into the high bits of the byte elements.
19310   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19311
19312   SDValue V = Op;
19313
19314   // v = v - ((v >> 1) & 0x55555555...)
19315   SDValue Srl =
19316       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19317   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19318   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19319
19320   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19321   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19322   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19323   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19324   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19325
19326   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19327   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19328   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19329   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19330
19331   // At this point, V contains the byte-wise population count, and we are
19332   // merely doing a horizontal sum if necessary to get the wider element
19333   // counts.
19334   if (EltVT == MVT::i8)
19335     return V;
19336
19337   return LowerHorizontalByteSum(
19338       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19339       DAG);
19340 }
19341
19342 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19343                                 SelectionDAG &DAG) {
19344   MVT VT = Op.getSimpleValueType();
19345   // FIXME: Need to add AVX-512 support here!
19346   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19347          "Unknown CTPOP type to handle");
19348   SDLoc DL(Op.getNode());
19349   SDValue Op0 = Op.getOperand(0);
19350
19351   if (!Subtarget->hasSSSE3()) {
19352     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19353     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19354     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19355   }
19356
19357   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19358     unsigned NumElems = VT.getVectorNumElements();
19359
19360     // Extract each 128-bit vector, compute pop count and concat the result.
19361     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19362     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19363
19364     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19365                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19366                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19367   }
19368
19369   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19370 }
19371
19372 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19373                           SelectionDAG &DAG) {
19374   assert(Op.getValueType().isVector() &&
19375          "We only do custom lowering for vector population count.");
19376   return LowerVectorCTPOP(Op, Subtarget, DAG);
19377 }
19378
19379 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19380   SDNode *Node = Op.getNode();
19381   SDLoc dl(Node);
19382   EVT T = Node->getValueType(0);
19383   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19384                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19385   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19386                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19387                        Node->getOperand(0),
19388                        Node->getOperand(1), negOp,
19389                        cast<AtomicSDNode>(Node)->getMemOperand(),
19390                        cast<AtomicSDNode>(Node)->getOrdering(),
19391                        cast<AtomicSDNode>(Node)->getSynchScope());
19392 }
19393
19394 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19395   SDNode *Node = Op.getNode();
19396   SDLoc dl(Node);
19397   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19398
19399   // Convert seq_cst store -> xchg
19400   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19401   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19402   //        (The only way to get a 16-byte store is cmpxchg16b)
19403   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19404   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19405       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19406     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19407                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19408                                  Node->getOperand(0),
19409                                  Node->getOperand(1), Node->getOperand(2),
19410                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19411                                  cast<AtomicSDNode>(Node)->getOrdering(),
19412                                  cast<AtomicSDNode>(Node)->getSynchScope());
19413     return Swap.getValue(1);
19414   }
19415   // Other atomic stores have a simple pattern.
19416   return Op;
19417 }
19418
19419 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19420   EVT VT = Op.getNode()->getSimpleValueType(0);
19421
19422   // Let legalize expand this if it isn't a legal type yet.
19423   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19424     return SDValue();
19425
19426   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19427
19428   unsigned Opc;
19429   bool ExtraOp = false;
19430   switch (Op.getOpcode()) {
19431   default: llvm_unreachable("Invalid code");
19432   case ISD::ADDC: Opc = X86ISD::ADD; break;
19433   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19434   case ISD::SUBC: Opc = X86ISD::SUB; break;
19435   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19436   }
19437
19438   if (!ExtraOp)
19439     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19440                        Op.getOperand(1));
19441   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19442                      Op.getOperand(1), Op.getOperand(2));
19443 }
19444
19445 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19446                             SelectionDAG &DAG) {
19447   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19448
19449   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19450   // which returns the values as { float, float } (in XMM0) or
19451   // { double, double } (which is returned in XMM0, XMM1).
19452   SDLoc dl(Op);
19453   SDValue Arg = Op.getOperand(0);
19454   EVT ArgVT = Arg.getValueType();
19455   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19456
19457   TargetLowering::ArgListTy Args;
19458   TargetLowering::ArgListEntry Entry;
19459
19460   Entry.Node = Arg;
19461   Entry.Ty = ArgTy;
19462   Entry.isSExt = false;
19463   Entry.isZExt = false;
19464   Args.push_back(Entry);
19465
19466   bool isF64 = ArgVT == MVT::f64;
19467   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19468   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19469   // the results are returned via SRet in memory.
19470   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19472   SDValue Callee =
19473       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19474
19475   Type *RetTy = isF64
19476     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19477     : (Type*)VectorType::get(ArgTy, 4);
19478
19479   TargetLowering::CallLoweringInfo CLI(DAG);
19480   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19481     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19482
19483   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19484
19485   if (isF64)
19486     // Returned in xmm0 and xmm1.
19487     return CallResult.first;
19488
19489   // Returned in bits 0:31 and 32:64 xmm0.
19490   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19491                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19492   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19493                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19494   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19495   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19496 }
19497
19498 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19499                              SelectionDAG &DAG) {
19500   assert(Subtarget->hasAVX512() &&
19501          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19502
19503   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19504   EVT VT = N->getValue().getValueType();
19505   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19506   SDLoc dl(Op);
19507
19508   // X86 scatter kills mask register, so its type should be added to
19509   // the list of return values
19510   if (N->getNumValues() == 1) {
19511     SDValue Index = N->getIndex();
19512     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19513         !Index.getValueType().is512BitVector())
19514       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19515
19516     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19517     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19518                       N->getOperand(3), Index };
19519
19520     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19521     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19522     return SDValue(NewScatter.getNode(), 0);
19523   }
19524   return Op;
19525 }
19526
19527 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19528                             SelectionDAG &DAG) {
19529   assert(Subtarget->hasAVX512() &&
19530          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19531
19532   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19533   EVT VT = Op.getValueType();
19534   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19535   SDLoc dl(Op);
19536
19537   SDValue Index = N->getIndex();
19538   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19539       !Index.getValueType().is512BitVector()) {
19540     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19541     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19542                       N->getOperand(3), Index };
19543     DAG.UpdateNodeOperands(N, Ops);
19544   }
19545   return Op;
19546 }
19547
19548 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19549                                                     SelectionDAG &DAG) const {
19550   // TODO: Eventually, the lowering of these nodes should be informed by or
19551   // deferred to the GC strategy for the function in which they appear. For
19552   // now, however, they must be lowered to something. Since they are logically
19553   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19554   // require special handling for these nodes), lower them as literal NOOPs for
19555   // the time being.
19556   SmallVector<SDValue, 2> Ops;
19557
19558   Ops.push_back(Op.getOperand(0));
19559   if (Op->getGluedNode())
19560     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19561
19562   SDLoc OpDL(Op);
19563   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19564   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19565
19566   return NOOP;
19567 }
19568
19569 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19570                                                   SelectionDAG &DAG) const {
19571   // TODO: Eventually, the lowering of these nodes should be informed by or
19572   // deferred to the GC strategy for the function in which they appear. For
19573   // now, however, they must be lowered to something. Since they are logically
19574   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19575   // require special handling for these nodes), lower them as literal NOOPs for
19576   // the time being.
19577   SmallVector<SDValue, 2> Ops;
19578
19579   Ops.push_back(Op.getOperand(0));
19580   if (Op->getGluedNode())
19581     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19582
19583   SDLoc OpDL(Op);
19584   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19585   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19586
19587   return NOOP;
19588 }
19589
19590 /// LowerOperation - Provide custom lowering hooks for some operations.
19591 ///
19592 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19593   switch (Op.getOpcode()) {
19594   default: llvm_unreachable("Should not custom lower this!");
19595   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19596   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19597     return LowerCMP_SWAP(Op, Subtarget, DAG);
19598   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19599   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19600   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19601   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19602   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19603   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19604   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19605   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19606   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19607   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19608   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19609   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19610   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19611   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19612   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19613   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19614   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19615   case ISD::SHL_PARTS:
19616   case ISD::SRA_PARTS:
19617   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19618   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19619   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19620   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19621   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19622   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19623   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19624   case ISD::SIGN_EXTEND_VECTOR_INREG:
19625     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19626   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19627   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19628   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19629   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19630   case ISD::FABS:
19631   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19632   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19633   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19634   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19635   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19636   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19637   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19638   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19639   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19640   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19641   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19642   case ISD::INTRINSIC_VOID:
19643   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19644   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19645   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19646   case ISD::FRAME_TO_ARGS_OFFSET:
19647                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19648   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19649   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19650   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19651   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19652   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19653   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19654   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19655   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
19656   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19657   case ISD::CTTZ:
19658   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19659   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19660   case ISD::UMUL_LOHI:
19661   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19662   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
19663   case ISD::SRA:
19664   case ISD::SRL:
19665   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19666   case ISD::SADDO:
19667   case ISD::UADDO:
19668   case ISD::SSUBO:
19669   case ISD::USUBO:
19670   case ISD::SMULO:
19671   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19672   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19673   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19674   case ISD::ADDC:
19675   case ISD::ADDE:
19676   case ISD::SUBC:
19677   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19678   case ISD::ADD:                return LowerADD(Op, DAG);
19679   case ISD::SUB:                return LowerSUB(Op, DAG);
19680   case ISD::SMAX:
19681   case ISD::SMIN:
19682   case ISD::UMAX:
19683   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19684   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19685   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19686   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19687   case ISD::GC_TRANSITION_START:
19688                                 return LowerGC_TRANSITION_START(Op, DAG);
19689   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19690   }
19691 }
19692
19693 /// ReplaceNodeResults - Replace a node with an illegal result type
19694 /// with a new node built out of custom code.
19695 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19696                                            SmallVectorImpl<SDValue>&Results,
19697                                            SelectionDAG &DAG) const {
19698   SDLoc dl(N);
19699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19700   switch (N->getOpcode()) {
19701   default:
19702     llvm_unreachable("Do not know how to custom type legalize this operation!");
19703   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19704   case X86ISD::FMINC:
19705   case X86ISD::FMIN:
19706   case X86ISD::FMAXC:
19707   case X86ISD::FMAX: {
19708     EVT VT = N->getValueType(0);
19709     if (VT != MVT::v2f32)
19710       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19711     SDValue UNDEF = DAG.getUNDEF(VT);
19712     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19713                               N->getOperand(0), UNDEF);
19714     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19715                               N->getOperand(1), UNDEF);
19716     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19717     return;
19718   }
19719   case ISD::SIGN_EXTEND_INREG:
19720   case ISD::ADDC:
19721   case ISD::ADDE:
19722   case ISD::SUBC:
19723   case ISD::SUBE:
19724     // We don't want to expand or promote these.
19725     return;
19726   case ISD::SDIV:
19727   case ISD::UDIV:
19728   case ISD::SREM:
19729   case ISD::UREM:
19730   case ISD::SDIVREM:
19731   case ISD::UDIVREM: {
19732     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19733     Results.push_back(V);
19734     return;
19735   }
19736   case ISD::FP_TO_SINT:
19737   case ISD::FP_TO_UINT: {
19738     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19739
19740     std::pair<SDValue,SDValue> Vals =
19741         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19742     SDValue FIST = Vals.first, StackSlot = Vals.second;
19743     if (FIST.getNode()) {
19744       EVT VT = N->getValueType(0);
19745       // Return a load from the stack slot.
19746       if (StackSlot.getNode())
19747         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19748                                       MachinePointerInfo(),
19749                                       false, false, false, 0));
19750       else
19751         Results.push_back(FIST);
19752     }
19753     return;
19754   }
19755   case ISD::UINT_TO_FP: {
19756     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19757     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19758         N->getValueType(0) != MVT::v2f32)
19759       return;
19760     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19761                                  N->getOperand(0));
19762     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19763                                      MVT::f64);
19764     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19765     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19766                              DAG.getBitcast(MVT::v2i64, VBias));
19767     Or = DAG.getBitcast(MVT::v2f64, Or);
19768     // TODO: Are there any fast-math-flags to propagate here?
19769     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19770     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19771     return;
19772   }
19773   case ISD::FP_ROUND: {
19774     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19775         return;
19776     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19777     Results.push_back(V);
19778     return;
19779   }
19780   case ISD::FP_EXTEND: {
19781     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19782     // No other ValueType for FP_EXTEND should reach this point.
19783     assert(N->getValueType(0) == MVT::v2f32 &&
19784            "Do not know how to legalize this Node");
19785     return;
19786   }
19787   case ISD::INTRINSIC_W_CHAIN: {
19788     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19789     switch (IntNo) {
19790     default : llvm_unreachable("Do not know how to custom type "
19791                                "legalize this intrinsic operation!");
19792     case Intrinsic::x86_rdtsc:
19793       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19794                                      Results);
19795     case Intrinsic::x86_rdtscp:
19796       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19797                                      Results);
19798     case Intrinsic::x86_rdpmc:
19799       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19800     }
19801   }
19802   case ISD::READCYCLECOUNTER: {
19803     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19804                                    Results);
19805   }
19806   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19807     EVT T = N->getValueType(0);
19808     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19809     bool Regs64bit = T == MVT::i128;
19810     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19811     SDValue cpInL, cpInH;
19812     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19813                         DAG.getConstant(0, dl, HalfT));
19814     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19815                         DAG.getConstant(1, dl, HalfT));
19816     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19817                              Regs64bit ? X86::RAX : X86::EAX,
19818                              cpInL, SDValue());
19819     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19820                              Regs64bit ? X86::RDX : X86::EDX,
19821                              cpInH, cpInL.getValue(1));
19822     SDValue swapInL, swapInH;
19823     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19824                           DAG.getConstant(0, dl, HalfT));
19825     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19826                           DAG.getConstant(1, dl, HalfT));
19827     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19828                                Regs64bit ? X86::RBX : X86::EBX,
19829                                swapInL, cpInH.getValue(1));
19830     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19831                                Regs64bit ? X86::RCX : X86::ECX,
19832                                swapInH, swapInL.getValue(1));
19833     SDValue Ops[] = { swapInH.getValue(0),
19834                       N->getOperand(1),
19835                       swapInH.getValue(1) };
19836     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19837     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19838     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19839                                   X86ISD::LCMPXCHG8_DAG;
19840     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19841     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19842                                         Regs64bit ? X86::RAX : X86::EAX,
19843                                         HalfT, Result.getValue(1));
19844     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19845                                         Regs64bit ? X86::RDX : X86::EDX,
19846                                         HalfT, cpOutL.getValue(2));
19847     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19848
19849     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19850                                         MVT::i32, cpOutH.getValue(2));
19851     SDValue Success =
19852         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19853                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19854     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19855
19856     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19857     Results.push_back(Success);
19858     Results.push_back(EFLAGS.getValue(1));
19859     return;
19860   }
19861   case ISD::ATOMIC_SWAP:
19862   case ISD::ATOMIC_LOAD_ADD:
19863   case ISD::ATOMIC_LOAD_SUB:
19864   case ISD::ATOMIC_LOAD_AND:
19865   case ISD::ATOMIC_LOAD_OR:
19866   case ISD::ATOMIC_LOAD_XOR:
19867   case ISD::ATOMIC_LOAD_NAND:
19868   case ISD::ATOMIC_LOAD_MIN:
19869   case ISD::ATOMIC_LOAD_MAX:
19870   case ISD::ATOMIC_LOAD_UMIN:
19871   case ISD::ATOMIC_LOAD_UMAX:
19872   case ISD::ATOMIC_LOAD: {
19873     // Delegate to generic TypeLegalization. Situations we can really handle
19874     // should have already been dealt with by AtomicExpandPass.cpp.
19875     break;
19876   }
19877   case ISD::BITCAST: {
19878     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19879     EVT DstVT = N->getValueType(0);
19880     EVT SrcVT = N->getOperand(0)->getValueType(0);
19881
19882     if (SrcVT != MVT::f64 ||
19883         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19884       return;
19885
19886     unsigned NumElts = DstVT.getVectorNumElements();
19887     EVT SVT = DstVT.getVectorElementType();
19888     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19889     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19890                                    MVT::v2f64, N->getOperand(0));
19891     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19892
19893     if (ExperimentalVectorWideningLegalization) {
19894       // If we are legalizing vectors by widening, we already have the desired
19895       // legal vector type, just return it.
19896       Results.push_back(ToVecInt);
19897       return;
19898     }
19899
19900     SmallVector<SDValue, 8> Elts;
19901     for (unsigned i = 0, e = NumElts; i != e; ++i)
19902       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19903                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19904
19905     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19906   }
19907   }
19908 }
19909
19910 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19911   switch ((X86ISD::NodeType)Opcode) {
19912   case X86ISD::FIRST_NUMBER:       break;
19913   case X86ISD::BSF:                return "X86ISD::BSF";
19914   case X86ISD::BSR:                return "X86ISD::BSR";
19915   case X86ISD::SHLD:               return "X86ISD::SHLD";
19916   case X86ISD::SHRD:               return "X86ISD::SHRD";
19917   case X86ISD::FAND:               return "X86ISD::FAND";
19918   case X86ISD::FANDN:              return "X86ISD::FANDN";
19919   case X86ISD::FOR:                return "X86ISD::FOR";
19920   case X86ISD::FXOR:               return "X86ISD::FXOR";
19921   case X86ISD::FILD:               return "X86ISD::FILD";
19922   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19923   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19924   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19925   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19926   case X86ISD::FLD:                return "X86ISD::FLD";
19927   case X86ISD::FST:                return "X86ISD::FST";
19928   case X86ISD::CALL:               return "X86ISD::CALL";
19929   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19930   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19931   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19932   case X86ISD::BT:                 return "X86ISD::BT";
19933   case X86ISD::CMP:                return "X86ISD::CMP";
19934   case X86ISD::COMI:               return "X86ISD::COMI";
19935   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19936   case X86ISD::CMPM:               return "X86ISD::CMPM";
19937   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19938   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19939   case X86ISD::SETCC:              return "X86ISD::SETCC";
19940   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19941   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19942   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19943   case X86ISD::CMOV:               return "X86ISD::CMOV";
19944   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19945   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19946   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19947   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19948   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19949   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19950   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19951   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19952   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19953   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19954   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19955   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19956   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19957   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19958   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19959   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19960   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19961   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19962   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19963   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19964   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19965   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19966   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19967   case X86ISD::HADD:               return "X86ISD::HADD";
19968   case X86ISD::HSUB:               return "X86ISD::HSUB";
19969   case X86ISD::FHADD:              return "X86ISD::FHADD";
19970   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19971   case X86ISD::ABS:                return "X86ISD::ABS";
19972   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19973   case X86ISD::FMAX:               return "X86ISD::FMAX";
19974   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19975   case X86ISD::FMIN:               return "X86ISD::FMIN";
19976   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19977   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19978   case X86ISD::FMINC:              return "X86ISD::FMINC";
19979   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19980   case X86ISD::FRCP:               return "X86ISD::FRCP";
19981   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19982   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19983   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19984   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19985   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19986   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19987   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19988   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19989   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19990   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19991   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19992   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19993   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19994   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19995   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19996   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19997   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19998   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19999   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20000   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20001   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20002   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20003   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20004   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20005   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20006   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20007   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20008   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20009   case X86ISD::VSHL:               return "X86ISD::VSHL";
20010   case X86ISD::VSRL:               return "X86ISD::VSRL";
20011   case X86ISD::VSRA:               return "X86ISD::VSRA";
20012   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20013   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20014   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20015   case X86ISD::CMPP:               return "X86ISD::CMPP";
20016   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20017   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20018   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20019   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20020   case X86ISD::ADD:                return "X86ISD::ADD";
20021   case X86ISD::SUB:                return "X86ISD::SUB";
20022   case X86ISD::ADC:                return "X86ISD::ADC";
20023   case X86ISD::SBB:                return "X86ISD::SBB";
20024   case X86ISD::SMUL:               return "X86ISD::SMUL";
20025   case X86ISD::UMUL:               return "X86ISD::UMUL";
20026   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20027   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20028   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20029   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20030   case X86ISD::INC:                return "X86ISD::INC";
20031   case X86ISD::DEC:                return "X86ISD::DEC";
20032   case X86ISD::OR:                 return "X86ISD::OR";
20033   case X86ISD::XOR:                return "X86ISD::XOR";
20034   case X86ISD::AND:                return "X86ISD::AND";
20035   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20036   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20037   case X86ISD::PTEST:              return "X86ISD::PTEST";
20038   case X86ISD::TESTP:              return "X86ISD::TESTP";
20039   case X86ISD::TESTM:              return "X86ISD::TESTM";
20040   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20041   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20042   case X86ISD::KTEST:              return "X86ISD::KTEST";
20043   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20044   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20045   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20046   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20047   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20048   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20049   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20050   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20051   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20052   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20053   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20054   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20055   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20056   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20057   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20058   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20059   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20060   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20061   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20062   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20063   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20064   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20065   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20066   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20067   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20068   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20069   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20070   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20071   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20072   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20073   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20074   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20075   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20076   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20077   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20078   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20079   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20080   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20081   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20082   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20083   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20084   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20085   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20086   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20087   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20088   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20089   case X86ISD::SAHF:               return "X86ISD::SAHF";
20090   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20091   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20092   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20093   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20094   case X86ISD::VPROT:              return "X86ISD::VPROT";
20095   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20096   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20097   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20098   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20099   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20100   case X86ISD::FMADD:              return "X86ISD::FMADD";
20101   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20102   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20103   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20104   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20105   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20106   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20107   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20108   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20109   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20110   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20111   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20112   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20113   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20114   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20115   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20116   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20117   case X86ISD::XTEST:              return "X86ISD::XTEST";
20118   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20119   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20120   case X86ISD::SELECT:             return "X86ISD::SELECT";
20121   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20122   case X86ISD::RCP28:              return "X86ISD::RCP28";
20123   case X86ISD::EXP2:               return "X86ISD::EXP2";
20124   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20125   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20126   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20127   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20128   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20129   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20130   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20131   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20132   case X86ISD::ADDS:               return "X86ISD::ADDS";
20133   case X86ISD::SUBS:               return "X86ISD::SUBS";
20134   case X86ISD::AVG:                return "X86ISD::AVG";
20135   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20136   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20137   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20138   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20139   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20140   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20141   }
20142   return nullptr;
20143 }
20144
20145 // isLegalAddressingMode - Return true if the addressing mode represented
20146 // by AM is legal for this target, for a load/store of the specified type.
20147 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20148                                               const AddrMode &AM, Type *Ty,
20149                                               unsigned AS) const {
20150   // X86 supports extremely general addressing modes.
20151   CodeModel::Model M = getTargetMachine().getCodeModel();
20152   Reloc::Model R = getTargetMachine().getRelocationModel();
20153
20154   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20155   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20156     return false;
20157
20158   if (AM.BaseGV) {
20159     unsigned GVFlags =
20160       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20161
20162     // If a reference to this global requires an extra load, we can't fold it.
20163     if (isGlobalStubReference(GVFlags))
20164       return false;
20165
20166     // If BaseGV requires a register for the PIC base, we cannot also have a
20167     // BaseReg specified.
20168     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20169       return false;
20170
20171     // If lower 4G is not available, then we must use rip-relative addressing.
20172     if ((M != CodeModel::Small || R != Reloc::Static) &&
20173         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20174       return false;
20175   }
20176
20177   switch (AM.Scale) {
20178   case 0:
20179   case 1:
20180   case 2:
20181   case 4:
20182   case 8:
20183     // These scales always work.
20184     break;
20185   case 3:
20186   case 5:
20187   case 9:
20188     // These scales are formed with basereg+scalereg.  Only accept if there is
20189     // no basereg yet.
20190     if (AM.HasBaseReg)
20191       return false;
20192     break;
20193   default:  // Other stuff never works.
20194     return false;
20195   }
20196
20197   return true;
20198 }
20199
20200 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20201   unsigned Bits = Ty->getScalarSizeInBits();
20202
20203   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20204   // particularly cheaper than those without.
20205   if (Bits == 8)
20206     return false;
20207
20208   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20209   // variable shifts just as cheap as scalar ones.
20210   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20211     return false;
20212
20213   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20214   // fully general vector.
20215   return true;
20216 }
20217
20218 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20219   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20220     return false;
20221   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20222   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20223   return NumBits1 > NumBits2;
20224 }
20225
20226 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20227   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20228     return false;
20229
20230   if (!isTypeLegal(EVT::getEVT(Ty1)))
20231     return false;
20232
20233   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20234
20235   // Assuming the caller doesn't have a zeroext or signext return parameter,
20236   // truncation all the way down to i1 is valid.
20237   return true;
20238 }
20239
20240 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20241   return isInt<32>(Imm);
20242 }
20243
20244 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20245   // Can also use sub to handle negated immediates.
20246   return isInt<32>(Imm);
20247 }
20248
20249 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20250   if (!VT1.isInteger() || !VT2.isInteger())
20251     return false;
20252   unsigned NumBits1 = VT1.getSizeInBits();
20253   unsigned NumBits2 = VT2.getSizeInBits();
20254   return NumBits1 > NumBits2;
20255 }
20256
20257 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20258   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20259   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20260 }
20261
20262 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20263   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20264   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20265 }
20266
20267 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20268   EVT VT1 = Val.getValueType();
20269   if (isZExtFree(VT1, VT2))
20270     return true;
20271
20272   if (Val.getOpcode() != ISD::LOAD)
20273     return false;
20274
20275   if (!VT1.isSimple() || !VT1.isInteger() ||
20276       !VT2.isSimple() || !VT2.isInteger())
20277     return false;
20278
20279   switch (VT1.getSimpleVT().SimpleTy) {
20280   default: break;
20281   case MVT::i8:
20282   case MVT::i16:
20283   case MVT::i32:
20284     // X86 has 8, 16, and 32-bit zero-extending loads.
20285     return true;
20286   }
20287
20288   return false;
20289 }
20290
20291 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20292
20293 bool
20294 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20295   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20296     return false;
20297
20298   VT = VT.getScalarType();
20299
20300   if (!VT.isSimple())
20301     return false;
20302
20303   switch (VT.getSimpleVT().SimpleTy) {
20304   case MVT::f32:
20305   case MVT::f64:
20306     return true;
20307   default:
20308     break;
20309   }
20310
20311   return false;
20312 }
20313
20314 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20315   // i16 instructions are longer (0x66 prefix) and potentially slower.
20316   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20317 }
20318
20319 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20320 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20321 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20322 /// are assumed to be legal.
20323 bool
20324 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20325                                       EVT VT) const {
20326   if (!VT.isSimple())
20327     return false;
20328
20329   // Not for i1 vectors
20330   if (VT.getScalarType() == MVT::i1)
20331     return false;
20332
20333   // Very little shuffling can be done for 64-bit vectors right now.
20334   if (VT.getSizeInBits() == 64)
20335     return false;
20336
20337   // We only care that the types being shuffled are legal. The lowering can
20338   // handle any possible shuffle mask that results.
20339   return isTypeLegal(VT.getSimpleVT());
20340 }
20341
20342 bool
20343 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20344                                           EVT VT) const {
20345   // Just delegate to the generic legality, clear masks aren't special.
20346   return isShuffleMaskLegal(Mask, VT);
20347 }
20348
20349 //===----------------------------------------------------------------------===//
20350 //                           X86 Scheduler Hooks
20351 //===----------------------------------------------------------------------===//
20352
20353 /// Utility function to emit xbegin specifying the start of an RTM region.
20354 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20355                                      const TargetInstrInfo *TII) {
20356   DebugLoc DL = MI->getDebugLoc();
20357
20358   const BasicBlock *BB = MBB->getBasicBlock();
20359   MachineFunction::iterator I = ++MBB->getIterator();
20360
20361   // For the v = xbegin(), we generate
20362   //
20363   // thisMBB:
20364   //  xbegin sinkMBB
20365   //
20366   // mainMBB:
20367   //  eax = -1
20368   //
20369   // sinkMBB:
20370   //  v = eax
20371
20372   MachineBasicBlock *thisMBB = MBB;
20373   MachineFunction *MF = MBB->getParent();
20374   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20375   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20376   MF->insert(I, mainMBB);
20377   MF->insert(I, sinkMBB);
20378
20379   // Transfer the remainder of BB and its successor edges to sinkMBB.
20380   sinkMBB->splice(sinkMBB->begin(), MBB,
20381                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20382   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20383
20384   // thisMBB:
20385   //  xbegin sinkMBB
20386   //  # fallthrough to mainMBB
20387   //  # abortion to sinkMBB
20388   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20389   thisMBB->addSuccessor(mainMBB);
20390   thisMBB->addSuccessor(sinkMBB);
20391
20392   // mainMBB:
20393   //  EAX = -1
20394   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20395   mainMBB->addSuccessor(sinkMBB);
20396
20397   // sinkMBB:
20398   // EAX is live into the sinkMBB
20399   sinkMBB->addLiveIn(X86::EAX);
20400   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20401           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20402     .addReg(X86::EAX);
20403
20404   MI->eraseFromParent();
20405   return sinkMBB;
20406 }
20407
20408 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20409 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20410 // in the .td file.
20411 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20412                                        const TargetInstrInfo *TII) {
20413   unsigned Opc;
20414   switch (MI->getOpcode()) {
20415   default: llvm_unreachable("illegal opcode!");
20416   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20417   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20418   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20419   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20420   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20421   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20422   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20423   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20424   }
20425
20426   DebugLoc dl = MI->getDebugLoc();
20427   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20428
20429   unsigned NumArgs = MI->getNumOperands();
20430   for (unsigned i = 1; i < NumArgs; ++i) {
20431     MachineOperand &Op = MI->getOperand(i);
20432     if (!(Op.isReg() && Op.isImplicit()))
20433       MIB.addOperand(Op);
20434   }
20435   if (MI->hasOneMemOperand())
20436     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20437
20438   BuildMI(*BB, MI, dl,
20439     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20440     .addReg(X86::XMM0);
20441
20442   MI->eraseFromParent();
20443   return BB;
20444 }
20445
20446 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20447 // defs in an instruction pattern
20448 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20449                                        const TargetInstrInfo *TII) {
20450   unsigned Opc;
20451   switch (MI->getOpcode()) {
20452   default: llvm_unreachable("illegal opcode!");
20453   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20454   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20455   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20456   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20457   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20458   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20459   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20460   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20461   }
20462
20463   DebugLoc dl = MI->getDebugLoc();
20464   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20465
20466   unsigned NumArgs = MI->getNumOperands(); // remove the results
20467   for (unsigned i = 1; i < NumArgs; ++i) {
20468     MachineOperand &Op = MI->getOperand(i);
20469     if (!(Op.isReg() && Op.isImplicit()))
20470       MIB.addOperand(Op);
20471   }
20472   if (MI->hasOneMemOperand())
20473     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20474
20475   BuildMI(*BB, MI, dl,
20476     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20477     .addReg(X86::ECX);
20478
20479   MI->eraseFromParent();
20480   return BB;
20481 }
20482
20483 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20484                                       const X86Subtarget *Subtarget) {
20485   DebugLoc dl = MI->getDebugLoc();
20486   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20487   // Address into RAX/EAX, other two args into ECX, EDX.
20488   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20489   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20490   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20491   for (int i = 0; i < X86::AddrNumOperands; ++i)
20492     MIB.addOperand(MI->getOperand(i));
20493
20494   unsigned ValOps = X86::AddrNumOperands;
20495   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20496     .addReg(MI->getOperand(ValOps).getReg());
20497   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20498     .addReg(MI->getOperand(ValOps+1).getReg());
20499
20500   // The instruction doesn't actually take any operands though.
20501   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20502
20503   MI->eraseFromParent(); // The pseudo is gone now.
20504   return BB;
20505 }
20506
20507 MachineBasicBlock *
20508 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20509                                                  MachineBasicBlock *MBB) const {
20510   // Emit va_arg instruction on X86-64.
20511
20512   // Operands to this pseudo-instruction:
20513   // 0  ) Output        : destination address (reg)
20514   // 1-5) Input         : va_list address (addr, i64mem)
20515   // 6  ) ArgSize       : Size (in bytes) of vararg type
20516   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20517   // 8  ) Align         : Alignment of type
20518   // 9  ) EFLAGS (implicit-def)
20519
20520   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20521   static_assert(X86::AddrNumOperands == 5,
20522                 "VAARG_64 assumes 5 address operands");
20523
20524   unsigned DestReg = MI->getOperand(0).getReg();
20525   MachineOperand &Base = MI->getOperand(1);
20526   MachineOperand &Scale = MI->getOperand(2);
20527   MachineOperand &Index = MI->getOperand(3);
20528   MachineOperand &Disp = MI->getOperand(4);
20529   MachineOperand &Segment = MI->getOperand(5);
20530   unsigned ArgSize = MI->getOperand(6).getImm();
20531   unsigned ArgMode = MI->getOperand(7).getImm();
20532   unsigned Align = MI->getOperand(8).getImm();
20533
20534   // Memory Reference
20535   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20536   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20537   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20538
20539   // Machine Information
20540   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20541   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20542   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20543   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20544   DebugLoc DL = MI->getDebugLoc();
20545
20546   // struct va_list {
20547   //   i32   gp_offset
20548   //   i32   fp_offset
20549   //   i64   overflow_area (address)
20550   //   i64   reg_save_area (address)
20551   // }
20552   // sizeof(va_list) = 24
20553   // alignment(va_list) = 8
20554
20555   unsigned TotalNumIntRegs = 6;
20556   unsigned TotalNumXMMRegs = 8;
20557   bool UseGPOffset = (ArgMode == 1);
20558   bool UseFPOffset = (ArgMode == 2);
20559   unsigned MaxOffset = TotalNumIntRegs * 8 +
20560                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20561
20562   /* Align ArgSize to a multiple of 8 */
20563   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20564   bool NeedsAlign = (Align > 8);
20565
20566   MachineBasicBlock *thisMBB = MBB;
20567   MachineBasicBlock *overflowMBB;
20568   MachineBasicBlock *offsetMBB;
20569   MachineBasicBlock *endMBB;
20570
20571   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20572   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20573   unsigned OffsetReg = 0;
20574
20575   if (!UseGPOffset && !UseFPOffset) {
20576     // If we only pull from the overflow region, we don't create a branch.
20577     // We don't need to alter control flow.
20578     OffsetDestReg = 0; // unused
20579     OverflowDestReg = DestReg;
20580
20581     offsetMBB = nullptr;
20582     overflowMBB = thisMBB;
20583     endMBB = thisMBB;
20584   } else {
20585     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20586     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20587     // If not, pull from overflow_area. (branch to overflowMBB)
20588     //
20589     //       thisMBB
20590     //         |     .
20591     //         |        .
20592     //     offsetMBB   overflowMBB
20593     //         |        .
20594     //         |     .
20595     //        endMBB
20596
20597     // Registers for the PHI in endMBB
20598     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20599     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20600
20601     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20602     MachineFunction *MF = MBB->getParent();
20603     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20604     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20605     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20606
20607     MachineFunction::iterator MBBIter = ++MBB->getIterator();
20608
20609     // Insert the new basic blocks
20610     MF->insert(MBBIter, offsetMBB);
20611     MF->insert(MBBIter, overflowMBB);
20612     MF->insert(MBBIter, endMBB);
20613
20614     // Transfer the remainder of MBB and its successor edges to endMBB.
20615     endMBB->splice(endMBB->begin(), thisMBB,
20616                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20617     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20618
20619     // Make offsetMBB and overflowMBB successors of thisMBB
20620     thisMBB->addSuccessor(offsetMBB);
20621     thisMBB->addSuccessor(overflowMBB);
20622
20623     // endMBB is a successor of both offsetMBB and overflowMBB
20624     offsetMBB->addSuccessor(endMBB);
20625     overflowMBB->addSuccessor(endMBB);
20626
20627     // Load the offset value into a register
20628     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20629     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20630       .addOperand(Base)
20631       .addOperand(Scale)
20632       .addOperand(Index)
20633       .addDisp(Disp, UseFPOffset ? 4 : 0)
20634       .addOperand(Segment)
20635       .setMemRefs(MMOBegin, MMOEnd);
20636
20637     // Check if there is enough room left to pull this argument.
20638     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20639       .addReg(OffsetReg)
20640       .addImm(MaxOffset + 8 - ArgSizeA8);
20641
20642     // Branch to "overflowMBB" if offset >= max
20643     // Fall through to "offsetMBB" otherwise
20644     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20645       .addMBB(overflowMBB);
20646   }
20647
20648   // In offsetMBB, emit code to use the reg_save_area.
20649   if (offsetMBB) {
20650     assert(OffsetReg != 0);
20651
20652     // Read the reg_save_area address.
20653     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20654     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20655       .addOperand(Base)
20656       .addOperand(Scale)
20657       .addOperand(Index)
20658       .addDisp(Disp, 16)
20659       .addOperand(Segment)
20660       .setMemRefs(MMOBegin, MMOEnd);
20661
20662     // Zero-extend the offset
20663     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20664       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20665         .addImm(0)
20666         .addReg(OffsetReg)
20667         .addImm(X86::sub_32bit);
20668
20669     // Add the offset to the reg_save_area to get the final address.
20670     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20671       .addReg(OffsetReg64)
20672       .addReg(RegSaveReg);
20673
20674     // Compute the offset for the next argument
20675     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20676     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20677       .addReg(OffsetReg)
20678       .addImm(UseFPOffset ? 16 : 8);
20679
20680     // Store it back into the va_list.
20681     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20682       .addOperand(Base)
20683       .addOperand(Scale)
20684       .addOperand(Index)
20685       .addDisp(Disp, UseFPOffset ? 4 : 0)
20686       .addOperand(Segment)
20687       .addReg(NextOffsetReg)
20688       .setMemRefs(MMOBegin, MMOEnd);
20689
20690     // Jump to endMBB
20691     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20692       .addMBB(endMBB);
20693   }
20694
20695   //
20696   // Emit code to use overflow area
20697   //
20698
20699   // Load the overflow_area address into a register.
20700   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20701   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20702     .addOperand(Base)
20703     .addOperand(Scale)
20704     .addOperand(Index)
20705     .addDisp(Disp, 8)
20706     .addOperand(Segment)
20707     .setMemRefs(MMOBegin, MMOEnd);
20708
20709   // If we need to align it, do so. Otherwise, just copy the address
20710   // to OverflowDestReg.
20711   if (NeedsAlign) {
20712     // Align the overflow address
20713     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20714     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20715
20716     // aligned_addr = (addr + (align-1)) & ~(align-1)
20717     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20718       .addReg(OverflowAddrReg)
20719       .addImm(Align-1);
20720
20721     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20722       .addReg(TmpReg)
20723       .addImm(~(uint64_t)(Align-1));
20724   } else {
20725     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20726       .addReg(OverflowAddrReg);
20727   }
20728
20729   // Compute the next overflow address after this argument.
20730   // (the overflow address should be kept 8-byte aligned)
20731   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20732   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20733     .addReg(OverflowDestReg)
20734     .addImm(ArgSizeA8);
20735
20736   // Store the new overflow address.
20737   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20738     .addOperand(Base)
20739     .addOperand(Scale)
20740     .addOperand(Index)
20741     .addDisp(Disp, 8)
20742     .addOperand(Segment)
20743     .addReg(NextAddrReg)
20744     .setMemRefs(MMOBegin, MMOEnd);
20745
20746   // If we branched, emit the PHI to the front of endMBB.
20747   if (offsetMBB) {
20748     BuildMI(*endMBB, endMBB->begin(), DL,
20749             TII->get(X86::PHI), DestReg)
20750       .addReg(OffsetDestReg).addMBB(offsetMBB)
20751       .addReg(OverflowDestReg).addMBB(overflowMBB);
20752   }
20753
20754   // Erase the pseudo instruction
20755   MI->eraseFromParent();
20756
20757   return endMBB;
20758 }
20759
20760 MachineBasicBlock *
20761 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20762                                                  MachineInstr *MI,
20763                                                  MachineBasicBlock *MBB) const {
20764   // Emit code to save XMM registers to the stack. The ABI says that the
20765   // number of registers to save is given in %al, so it's theoretically
20766   // possible to do an indirect jump trick to avoid saving all of them,
20767   // however this code takes a simpler approach and just executes all
20768   // of the stores if %al is non-zero. It's less code, and it's probably
20769   // easier on the hardware branch predictor, and stores aren't all that
20770   // expensive anyway.
20771
20772   // Create the new basic blocks. One block contains all the XMM stores,
20773   // and one block is the final destination regardless of whether any
20774   // stores were performed.
20775   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20776   MachineFunction *F = MBB->getParent();
20777   MachineFunction::iterator MBBIter = ++MBB->getIterator();
20778   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20779   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20780   F->insert(MBBIter, XMMSaveMBB);
20781   F->insert(MBBIter, EndMBB);
20782
20783   // Transfer the remainder of MBB and its successor edges to EndMBB.
20784   EndMBB->splice(EndMBB->begin(), MBB,
20785                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20786   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20787
20788   // The original block will now fall through to the XMM save block.
20789   MBB->addSuccessor(XMMSaveMBB);
20790   // The XMMSaveMBB will fall through to the end block.
20791   XMMSaveMBB->addSuccessor(EndMBB);
20792
20793   // Now add the instructions.
20794   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20795   DebugLoc DL = MI->getDebugLoc();
20796
20797   unsigned CountReg = MI->getOperand(0).getReg();
20798   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20799   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20800
20801   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20802     // If %al is 0, branch around the XMM save block.
20803     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20804     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20805     MBB->addSuccessor(EndMBB);
20806   }
20807
20808   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20809   // that was just emitted, but clearly shouldn't be "saved".
20810   assert((MI->getNumOperands() <= 3 ||
20811           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20812           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20813          && "Expected last argument to be EFLAGS");
20814   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20815   // In the XMM save block, save all the XMM argument registers.
20816   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20817     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20818     MachineMemOperand *MMO = F->getMachineMemOperand(
20819         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20820         MachineMemOperand::MOStore,
20821         /*Size=*/16, /*Align=*/16);
20822     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20823       .addFrameIndex(RegSaveFrameIndex)
20824       .addImm(/*Scale=*/1)
20825       .addReg(/*IndexReg=*/0)
20826       .addImm(/*Disp=*/Offset)
20827       .addReg(/*Segment=*/0)
20828       .addReg(MI->getOperand(i).getReg())
20829       .addMemOperand(MMO);
20830   }
20831
20832   MI->eraseFromParent();   // The pseudo instruction is gone now.
20833
20834   return EndMBB;
20835 }
20836
20837 // The EFLAGS operand of SelectItr might be missing a kill marker
20838 // because there were multiple uses of EFLAGS, and ISel didn't know
20839 // which to mark. Figure out whether SelectItr should have had a
20840 // kill marker, and set it if it should. Returns the correct kill
20841 // marker value.
20842 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20843                                      MachineBasicBlock* BB,
20844                                      const TargetRegisterInfo* TRI) {
20845   // Scan forward through BB for a use/def of EFLAGS.
20846   MachineBasicBlock::iterator miI(std::next(SelectItr));
20847   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20848     const MachineInstr& mi = *miI;
20849     if (mi.readsRegister(X86::EFLAGS))
20850       return false;
20851     if (mi.definesRegister(X86::EFLAGS))
20852       break; // Should have kill-flag - update below.
20853   }
20854
20855   // If we hit the end of the block, check whether EFLAGS is live into a
20856   // successor.
20857   if (miI == BB->end()) {
20858     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20859                                           sEnd = BB->succ_end();
20860          sItr != sEnd; ++sItr) {
20861       MachineBasicBlock* succ = *sItr;
20862       if (succ->isLiveIn(X86::EFLAGS))
20863         return false;
20864     }
20865   }
20866
20867   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20868   // out. SelectMI should have a kill flag on EFLAGS.
20869   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20870   return true;
20871 }
20872
20873 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20874 // together with other CMOV pseudo-opcodes into a single basic-block with
20875 // conditional jump around it.
20876 static bool isCMOVPseudo(MachineInstr *MI) {
20877   switch (MI->getOpcode()) {
20878   case X86::CMOV_FR32:
20879   case X86::CMOV_FR64:
20880   case X86::CMOV_GR8:
20881   case X86::CMOV_GR16:
20882   case X86::CMOV_GR32:
20883   case X86::CMOV_RFP32:
20884   case X86::CMOV_RFP64:
20885   case X86::CMOV_RFP80:
20886   case X86::CMOV_V2F64:
20887   case X86::CMOV_V2I64:
20888   case X86::CMOV_V4F32:
20889   case X86::CMOV_V4F64:
20890   case X86::CMOV_V4I64:
20891   case X86::CMOV_V16F32:
20892   case X86::CMOV_V8F32:
20893   case X86::CMOV_V8F64:
20894   case X86::CMOV_V8I64:
20895   case X86::CMOV_V8I1:
20896   case X86::CMOV_V16I1:
20897   case X86::CMOV_V32I1:
20898   case X86::CMOV_V64I1:
20899     return true;
20900
20901   default:
20902     return false;
20903   }
20904 }
20905
20906 MachineBasicBlock *
20907 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20908                                      MachineBasicBlock *BB) const {
20909   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20910   DebugLoc DL = MI->getDebugLoc();
20911
20912   // To "insert" a SELECT_CC instruction, we actually have to insert the
20913   // diamond control-flow pattern.  The incoming instruction knows the
20914   // destination vreg to set, the condition code register to branch on, the
20915   // true/false values to select between, and a branch opcode to use.
20916   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20917   MachineFunction::iterator It = ++BB->getIterator();
20918
20919   //  thisMBB:
20920   //  ...
20921   //   TrueVal = ...
20922   //   cmpTY ccX, r1, r2
20923   //   bCC copy1MBB
20924   //   fallthrough --> copy0MBB
20925   MachineBasicBlock *thisMBB = BB;
20926   MachineFunction *F = BB->getParent();
20927
20928   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20929   // as described above, by inserting a BB, and then making a PHI at the join
20930   // point to select the true and false operands of the CMOV in the PHI.
20931   //
20932   // The code also handles two different cases of multiple CMOV opcodes
20933   // in a row.
20934   //
20935   // Case 1:
20936   // In this case, there are multiple CMOVs in a row, all which are based on
20937   // the same condition setting (or the exact opposite condition setting).
20938   // In this case we can lower all the CMOVs using a single inserted BB, and
20939   // then make a number of PHIs at the join point to model the CMOVs. The only
20940   // trickiness here, is that in a case like:
20941   //
20942   // t2 = CMOV cond1 t1, f1
20943   // t3 = CMOV cond1 t2, f2
20944   //
20945   // when rewriting this into PHIs, we have to perform some renaming on the
20946   // temps since you cannot have a PHI operand refer to a PHI result earlier
20947   // in the same block.  The "simple" but wrong lowering would be:
20948   //
20949   // t2 = PHI t1(BB1), f1(BB2)
20950   // t3 = PHI t2(BB1), f2(BB2)
20951   //
20952   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20953   // renaming is to note that on the path through BB1, t2 is really just a
20954   // copy of t1, and do that renaming, properly generating:
20955   //
20956   // t2 = PHI t1(BB1), f1(BB2)
20957   // t3 = PHI t1(BB1), f2(BB2)
20958   //
20959   // Case 2, we lower cascaded CMOVs such as
20960   //
20961   //   (CMOV (CMOV F, T, cc1), T, cc2)
20962   //
20963   // to two successives branches.  For that, we look for another CMOV as the
20964   // following instruction.
20965   //
20966   // Without this, we would add a PHI between the two jumps, which ends up
20967   // creating a few copies all around. For instance, for
20968   //
20969   //    (sitofp (zext (fcmp une)))
20970   //
20971   // we would generate:
20972   //
20973   //         ucomiss %xmm1, %xmm0
20974   //         movss  <1.0f>, %xmm0
20975   //         movaps  %xmm0, %xmm1
20976   //         jne     .LBB5_2
20977   //         xorps   %xmm1, %xmm1
20978   // .LBB5_2:
20979   //         jp      .LBB5_4
20980   //         movaps  %xmm1, %xmm0
20981   // .LBB5_4:
20982   //         retq
20983   //
20984   // because this custom-inserter would have generated:
20985   //
20986   //   A
20987   //   | \
20988   //   |  B
20989   //   | /
20990   //   C
20991   //   | \
20992   //   |  D
20993   //   | /
20994   //   E
20995   //
20996   // A: X = ...; Y = ...
20997   // B: empty
20998   // C: Z = PHI [X, A], [Y, B]
20999   // D: empty
21000   // E: PHI [X, C], [Z, D]
21001   //
21002   // If we lower both CMOVs in a single step, we can instead generate:
21003   //
21004   //   A
21005   //   | \
21006   //   |  C
21007   //   | /|
21008   //   |/ |
21009   //   |  |
21010   //   |  D
21011   //   | /
21012   //   E
21013   //
21014   // A: X = ...; Y = ...
21015   // D: empty
21016   // E: PHI [X, A], [X, C], [Y, D]
21017   //
21018   // Which, in our sitofp/fcmp example, gives us something like:
21019   //
21020   //         ucomiss %xmm1, %xmm0
21021   //         movss  <1.0f>, %xmm0
21022   //         jne     .LBB5_4
21023   //         jp      .LBB5_4
21024   //         xorps   %xmm0, %xmm0
21025   // .LBB5_4:
21026   //         retq
21027   //
21028   MachineInstr *CascadedCMOV = nullptr;
21029   MachineInstr *LastCMOV = MI;
21030   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21031   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21032   MachineBasicBlock::iterator NextMIIt =
21033       std::next(MachineBasicBlock::iterator(MI));
21034
21035   // Check for case 1, where there are multiple CMOVs with the same condition
21036   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21037   // number of jumps the most.
21038
21039   if (isCMOVPseudo(MI)) {
21040     // See if we have a string of CMOVS with the same condition.
21041     while (NextMIIt != BB->end() &&
21042            isCMOVPseudo(NextMIIt) &&
21043            (NextMIIt->getOperand(3).getImm() == CC ||
21044             NextMIIt->getOperand(3).getImm() == OppCC)) {
21045       LastCMOV = &*NextMIIt;
21046       ++NextMIIt;
21047     }
21048   }
21049
21050   // This checks for case 2, but only do this if we didn't already find
21051   // case 1, as indicated by LastCMOV == MI.
21052   if (LastCMOV == MI &&
21053       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21054       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21055       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21056     CascadedCMOV = &*NextMIIt;
21057   }
21058
21059   MachineBasicBlock *jcc1MBB = nullptr;
21060
21061   // If we have a cascaded CMOV, we lower it to two successive branches to
21062   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21063   if (CascadedCMOV) {
21064     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21065     F->insert(It, jcc1MBB);
21066     jcc1MBB->addLiveIn(X86::EFLAGS);
21067   }
21068
21069   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21070   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21071   F->insert(It, copy0MBB);
21072   F->insert(It, sinkMBB);
21073
21074   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21075   // live into the sink and copy blocks.
21076   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21077
21078   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21079   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21080       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21081     copy0MBB->addLiveIn(X86::EFLAGS);
21082     sinkMBB->addLiveIn(X86::EFLAGS);
21083   }
21084
21085   // Transfer the remainder of BB and its successor edges to sinkMBB.
21086   sinkMBB->splice(sinkMBB->begin(), BB,
21087                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21088   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21089
21090   // Add the true and fallthrough blocks as its successors.
21091   if (CascadedCMOV) {
21092     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21093     BB->addSuccessor(jcc1MBB);
21094
21095     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21096     // jump to the sinkMBB.
21097     jcc1MBB->addSuccessor(copy0MBB);
21098     jcc1MBB->addSuccessor(sinkMBB);
21099   } else {
21100     BB->addSuccessor(copy0MBB);
21101   }
21102
21103   // The true block target of the first (or only) branch is always sinkMBB.
21104   BB->addSuccessor(sinkMBB);
21105
21106   // Create the conditional branch instruction.
21107   unsigned Opc = X86::GetCondBranchFromCond(CC);
21108   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21109
21110   if (CascadedCMOV) {
21111     unsigned Opc2 = X86::GetCondBranchFromCond(
21112         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21113     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21114   }
21115
21116   //  copy0MBB:
21117   //   %FalseValue = ...
21118   //   # fallthrough to sinkMBB
21119   copy0MBB->addSuccessor(sinkMBB);
21120
21121   //  sinkMBB:
21122   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21123   //  ...
21124   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21125   MachineBasicBlock::iterator MIItEnd =
21126     std::next(MachineBasicBlock::iterator(LastCMOV));
21127   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21128   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21129   MachineInstrBuilder MIB;
21130
21131   // As we are creating the PHIs, we have to be careful if there is more than
21132   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21133   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21134   // That also means that PHI construction must work forward from earlier to
21135   // later, and that the code must maintain a mapping from earlier PHI's
21136   // destination registers, and the registers that went into the PHI.
21137
21138   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21139     unsigned DestReg = MIIt->getOperand(0).getReg();
21140     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21141     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21142
21143     // If this CMOV we are generating is the opposite condition from
21144     // the jump we generated, then we have to swap the operands for the
21145     // PHI that is going to be generated.
21146     if (MIIt->getOperand(3).getImm() == OppCC)
21147         std::swap(Op1Reg, Op2Reg);
21148
21149     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21150       Op1Reg = RegRewriteTable[Op1Reg].first;
21151
21152     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21153       Op2Reg = RegRewriteTable[Op2Reg].second;
21154
21155     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21156                   TII->get(X86::PHI), DestReg)
21157           .addReg(Op1Reg).addMBB(copy0MBB)
21158           .addReg(Op2Reg).addMBB(thisMBB);
21159
21160     // Add this PHI to the rewrite table.
21161     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21162   }
21163
21164   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21165   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21166   if (CascadedCMOV) {
21167     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21168     // Copy the PHI result to the register defined by the second CMOV.
21169     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21170             DL, TII->get(TargetOpcode::COPY),
21171             CascadedCMOV->getOperand(0).getReg())
21172         .addReg(MI->getOperand(0).getReg());
21173     CascadedCMOV->eraseFromParent();
21174   }
21175
21176   // Now remove the CMOV(s).
21177   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21178     (MIIt++)->eraseFromParent();
21179
21180   return sinkMBB;
21181 }
21182
21183 MachineBasicBlock *
21184 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21185                                        MachineBasicBlock *BB) const {
21186   // Combine the following atomic floating-point modification pattern:
21187   //   a.store(reg OP a.load(acquire), release)
21188   // Transform them into:
21189   //   OPss (%gpr), %xmm
21190   //   movss %xmm, (%gpr)
21191   // Or sd equivalent for 64-bit operations.
21192   unsigned MOp, FOp;
21193   switch (MI->getOpcode()) {
21194   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21195   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21196   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21197   }
21198   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21199   DebugLoc DL = MI->getDebugLoc();
21200   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21201   MachineOperand MSrc = MI->getOperand(0);
21202   unsigned VSrc = MI->getOperand(5).getReg();
21203   const MachineOperand &Disp = MI->getOperand(3);
21204   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21205   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21206   if (hasDisp && MSrc.isReg())
21207     MSrc.setIsKill(false);
21208   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21209                                 .addOperand(/*Base=*/MSrc)
21210                                 .addImm(/*Scale=*/1)
21211                                 .addReg(/*Index=*/0)
21212                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21213                                 .addReg(0);
21214   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21215                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21216                           .addReg(VSrc)
21217                           .addOperand(/*Base=*/MSrc)
21218                           .addImm(/*Scale=*/1)
21219                           .addReg(/*Index=*/0)
21220                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21221                           .addReg(/*Segment=*/0);
21222   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21223   MI->eraseFromParent(); // The pseudo instruction is gone now.
21224   return BB;
21225 }
21226
21227 MachineBasicBlock *
21228 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21229                                         MachineBasicBlock *BB) const {
21230   MachineFunction *MF = BB->getParent();
21231   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21232   DebugLoc DL = MI->getDebugLoc();
21233   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21234
21235   assert(MF->shouldSplitStack());
21236
21237   const bool Is64Bit = Subtarget->is64Bit();
21238   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21239
21240   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21241   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21242
21243   // BB:
21244   //  ... [Till the alloca]
21245   // If stacklet is not large enough, jump to mallocMBB
21246   //
21247   // bumpMBB:
21248   //  Allocate by subtracting from RSP
21249   //  Jump to continueMBB
21250   //
21251   // mallocMBB:
21252   //  Allocate by call to runtime
21253   //
21254   // continueMBB:
21255   //  ...
21256   //  [rest of original BB]
21257   //
21258
21259   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21260   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21261   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21262
21263   MachineRegisterInfo &MRI = MF->getRegInfo();
21264   const TargetRegisterClass *AddrRegClass =
21265       getRegClassFor(getPointerTy(MF->getDataLayout()));
21266
21267   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21268     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21269     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21270     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21271     sizeVReg = MI->getOperand(1).getReg(),
21272     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21273
21274   MachineFunction::iterator MBBIter = ++BB->getIterator();
21275
21276   MF->insert(MBBIter, bumpMBB);
21277   MF->insert(MBBIter, mallocMBB);
21278   MF->insert(MBBIter, continueMBB);
21279
21280   continueMBB->splice(continueMBB->begin(), BB,
21281                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21282   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21283
21284   // Add code to the main basic block to check if the stack limit has been hit,
21285   // and if so, jump to mallocMBB otherwise to bumpMBB.
21286   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21287   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21288     .addReg(tmpSPVReg).addReg(sizeVReg);
21289   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21290     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21291     .addReg(SPLimitVReg);
21292   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21293
21294   // bumpMBB simply decreases the stack pointer, since we know the current
21295   // stacklet has enough space.
21296   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21297     .addReg(SPLimitVReg);
21298   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21299     .addReg(SPLimitVReg);
21300   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21301
21302   // Calls into a routine in libgcc to allocate more space from the heap.
21303   const uint32_t *RegMask =
21304       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21305   if (IsLP64) {
21306     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21307       .addReg(sizeVReg);
21308     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21309       .addExternalSymbol("__morestack_allocate_stack_space")
21310       .addRegMask(RegMask)
21311       .addReg(X86::RDI, RegState::Implicit)
21312       .addReg(X86::RAX, RegState::ImplicitDefine);
21313   } else if (Is64Bit) {
21314     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21315       .addReg(sizeVReg);
21316     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21317       .addExternalSymbol("__morestack_allocate_stack_space")
21318       .addRegMask(RegMask)
21319       .addReg(X86::EDI, RegState::Implicit)
21320       .addReg(X86::EAX, RegState::ImplicitDefine);
21321   } else {
21322     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21323       .addImm(12);
21324     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21325     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21326       .addExternalSymbol("__morestack_allocate_stack_space")
21327       .addRegMask(RegMask)
21328       .addReg(X86::EAX, RegState::ImplicitDefine);
21329   }
21330
21331   if (!Is64Bit)
21332     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21333       .addImm(16);
21334
21335   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21336     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21337   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21338
21339   // Set up the CFG correctly.
21340   BB->addSuccessor(bumpMBB);
21341   BB->addSuccessor(mallocMBB);
21342   mallocMBB->addSuccessor(continueMBB);
21343   bumpMBB->addSuccessor(continueMBB);
21344
21345   // Take care of the PHI nodes.
21346   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21347           MI->getOperand(0).getReg())
21348     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21349     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21350
21351   // Delete the original pseudo instruction.
21352   MI->eraseFromParent();
21353
21354   // And we're done.
21355   return continueMBB;
21356 }
21357
21358 MachineBasicBlock *
21359 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21360                                         MachineBasicBlock *BB) const {
21361   DebugLoc DL = MI->getDebugLoc();
21362
21363   assert(!Subtarget->isTargetMachO());
21364
21365   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21366                                                     DL);
21367
21368   MI->eraseFromParent();   // The pseudo instruction is gone now.
21369   return BB;
21370 }
21371
21372 MachineBasicBlock *
21373 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21374                                       MachineBasicBlock *BB) const {
21375   // This is pretty easy.  We're taking the value that we received from
21376   // our load from the relocation, sticking it in either RDI (x86-64)
21377   // or EAX and doing an indirect call.  The return value will then
21378   // be in the normal return register.
21379   MachineFunction *F = BB->getParent();
21380   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21381   DebugLoc DL = MI->getDebugLoc();
21382
21383   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21384   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21385
21386   // Get a register mask for the lowered call.
21387   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21388   // proper register mask.
21389   const uint32_t *RegMask =
21390       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21391   if (Subtarget->is64Bit()) {
21392     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21393                                       TII->get(X86::MOV64rm), X86::RDI)
21394     .addReg(X86::RIP)
21395     .addImm(0).addReg(0)
21396     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21397                       MI->getOperand(3).getTargetFlags())
21398     .addReg(0);
21399     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21400     addDirectMem(MIB, X86::RDI);
21401     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21402   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21403     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21404                                       TII->get(X86::MOV32rm), X86::EAX)
21405     .addReg(0)
21406     .addImm(0).addReg(0)
21407     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21408                       MI->getOperand(3).getTargetFlags())
21409     .addReg(0);
21410     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21411     addDirectMem(MIB, X86::EAX);
21412     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21413   } else {
21414     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21415                                       TII->get(X86::MOV32rm), X86::EAX)
21416     .addReg(TII->getGlobalBaseReg(F))
21417     .addImm(0).addReg(0)
21418     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21419                       MI->getOperand(3).getTargetFlags())
21420     .addReg(0);
21421     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21422     addDirectMem(MIB, X86::EAX);
21423     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21424   }
21425
21426   MI->eraseFromParent(); // The pseudo instruction is gone now.
21427   return BB;
21428 }
21429
21430 MachineBasicBlock *
21431 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21432                                     MachineBasicBlock *MBB) const {
21433   DebugLoc DL = MI->getDebugLoc();
21434   MachineFunction *MF = MBB->getParent();
21435   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21436   MachineRegisterInfo &MRI = MF->getRegInfo();
21437
21438   const BasicBlock *BB = MBB->getBasicBlock();
21439   MachineFunction::iterator I = ++MBB->getIterator();
21440
21441   // Memory Reference
21442   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21443   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21444
21445   unsigned DstReg;
21446   unsigned MemOpndSlot = 0;
21447
21448   unsigned CurOp = 0;
21449
21450   DstReg = MI->getOperand(CurOp++).getReg();
21451   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21452   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21453   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21454   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21455
21456   MemOpndSlot = CurOp;
21457
21458   MVT PVT = getPointerTy(MF->getDataLayout());
21459   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21460          "Invalid Pointer Size!");
21461
21462   // For v = setjmp(buf), we generate
21463   //
21464   // thisMBB:
21465   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21466   //  SjLjSetup restoreMBB
21467   //
21468   // mainMBB:
21469   //  v_main = 0
21470   //
21471   // sinkMBB:
21472   //  v = phi(main, restore)
21473   //
21474   // restoreMBB:
21475   //  if base pointer being used, load it from frame
21476   //  v_restore = 1
21477
21478   MachineBasicBlock *thisMBB = MBB;
21479   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21480   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21481   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21482   MF->insert(I, mainMBB);
21483   MF->insert(I, sinkMBB);
21484   MF->push_back(restoreMBB);
21485   restoreMBB->setHasAddressTaken();
21486
21487   MachineInstrBuilder MIB;
21488
21489   // Transfer the remainder of BB and its successor edges to sinkMBB.
21490   sinkMBB->splice(sinkMBB->begin(), MBB,
21491                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21492   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21493
21494   // thisMBB:
21495   unsigned PtrStoreOpc = 0;
21496   unsigned LabelReg = 0;
21497   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21498   Reloc::Model RM = MF->getTarget().getRelocationModel();
21499   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21500                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21501
21502   // Prepare IP either in reg or imm.
21503   if (!UseImmLabel) {
21504     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21505     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21506     LabelReg = MRI.createVirtualRegister(PtrRC);
21507     if (Subtarget->is64Bit()) {
21508       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21509               .addReg(X86::RIP)
21510               .addImm(0)
21511               .addReg(0)
21512               .addMBB(restoreMBB)
21513               .addReg(0);
21514     } else {
21515       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21516       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21517               .addReg(XII->getGlobalBaseReg(MF))
21518               .addImm(0)
21519               .addReg(0)
21520               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21521               .addReg(0);
21522     }
21523   } else
21524     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21525   // Store IP
21526   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21527   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21528     if (i == X86::AddrDisp)
21529       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21530     else
21531       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21532   }
21533   if (!UseImmLabel)
21534     MIB.addReg(LabelReg);
21535   else
21536     MIB.addMBB(restoreMBB);
21537   MIB.setMemRefs(MMOBegin, MMOEnd);
21538   // Setup
21539   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21540           .addMBB(restoreMBB);
21541
21542   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21543   MIB.addRegMask(RegInfo->getNoPreservedMask());
21544   thisMBB->addSuccessor(mainMBB);
21545   thisMBB->addSuccessor(restoreMBB);
21546
21547   // mainMBB:
21548   //  EAX = 0
21549   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21550   mainMBB->addSuccessor(sinkMBB);
21551
21552   // sinkMBB:
21553   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21554           TII->get(X86::PHI), DstReg)
21555     .addReg(mainDstReg).addMBB(mainMBB)
21556     .addReg(restoreDstReg).addMBB(restoreMBB);
21557
21558   // restoreMBB:
21559   if (RegInfo->hasBasePointer(*MF)) {
21560     const bool Uses64BitFramePtr =
21561         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21562     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21563     X86FI->setRestoreBasePointer(MF);
21564     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21565     unsigned BasePtr = RegInfo->getBaseRegister();
21566     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21567     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21568                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21569       .setMIFlag(MachineInstr::FrameSetup);
21570   }
21571   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21572   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21573   restoreMBB->addSuccessor(sinkMBB);
21574
21575   MI->eraseFromParent();
21576   return sinkMBB;
21577 }
21578
21579 MachineBasicBlock *
21580 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21581                                      MachineBasicBlock *MBB) const {
21582   DebugLoc DL = MI->getDebugLoc();
21583   MachineFunction *MF = MBB->getParent();
21584   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21585   MachineRegisterInfo &MRI = MF->getRegInfo();
21586
21587   // Memory Reference
21588   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21589   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21590
21591   MVT PVT = getPointerTy(MF->getDataLayout());
21592   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21593          "Invalid Pointer Size!");
21594
21595   const TargetRegisterClass *RC =
21596     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21597   unsigned Tmp = MRI.createVirtualRegister(RC);
21598   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21599   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21600   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21601   unsigned SP = RegInfo->getStackRegister();
21602
21603   MachineInstrBuilder MIB;
21604
21605   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21606   const int64_t SPOffset = 2 * PVT.getStoreSize();
21607
21608   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21609   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21610
21611   // Reload FP
21612   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21613   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21614     MIB.addOperand(MI->getOperand(i));
21615   MIB.setMemRefs(MMOBegin, MMOEnd);
21616   // Reload IP
21617   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21618   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21619     if (i == X86::AddrDisp)
21620       MIB.addDisp(MI->getOperand(i), LabelOffset);
21621     else
21622       MIB.addOperand(MI->getOperand(i));
21623   }
21624   MIB.setMemRefs(MMOBegin, MMOEnd);
21625   // Reload SP
21626   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21627   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21628     if (i == X86::AddrDisp)
21629       MIB.addDisp(MI->getOperand(i), SPOffset);
21630     else
21631       MIB.addOperand(MI->getOperand(i));
21632   }
21633   MIB.setMemRefs(MMOBegin, MMOEnd);
21634   // Jump
21635   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21636
21637   MI->eraseFromParent();
21638   return MBB;
21639 }
21640
21641 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21642 // accumulator loops. Writing back to the accumulator allows the coalescer
21643 // to remove extra copies in the loop.
21644 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21645 MachineBasicBlock *
21646 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21647                                  MachineBasicBlock *MBB) const {
21648   MachineOperand &AddendOp = MI->getOperand(3);
21649
21650   // Bail out early if the addend isn't a register - we can't switch these.
21651   if (!AddendOp.isReg())
21652     return MBB;
21653
21654   MachineFunction &MF = *MBB->getParent();
21655   MachineRegisterInfo &MRI = MF.getRegInfo();
21656
21657   // Check whether the addend is defined by a PHI:
21658   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21659   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21660   if (!AddendDef.isPHI())
21661     return MBB;
21662
21663   // Look for the following pattern:
21664   // loop:
21665   //   %addend = phi [%entry, 0], [%loop, %result]
21666   //   ...
21667   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21668
21669   // Replace with:
21670   //   loop:
21671   //   %addend = phi [%entry, 0], [%loop, %result]
21672   //   ...
21673   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21674
21675   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21676     assert(AddendDef.getOperand(i).isReg());
21677     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21678     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21679     if (&PHISrcInst == MI) {
21680       // Found a matching instruction.
21681       unsigned NewFMAOpc = 0;
21682       switch (MI->getOpcode()) {
21683         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21684         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21685         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21686         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21687         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21688         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21689         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21690         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21691         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21692         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21693         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21694         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21695         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21696         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21697         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21698         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21699         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21700         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21701         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21702         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21703
21704         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21705         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21706         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21707         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21708         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21709         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21710         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21711         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21712         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21713         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21714         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21715         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21716         default: llvm_unreachable("Unrecognized FMA variant.");
21717       }
21718
21719       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21720       MachineInstrBuilder MIB =
21721         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21722         .addOperand(MI->getOperand(0))
21723         .addOperand(MI->getOperand(3))
21724         .addOperand(MI->getOperand(2))
21725         .addOperand(MI->getOperand(1));
21726       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21727       MI->eraseFromParent();
21728     }
21729   }
21730
21731   return MBB;
21732 }
21733
21734 MachineBasicBlock *
21735 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21736                                                MachineBasicBlock *BB) const {
21737   switch (MI->getOpcode()) {
21738   default: llvm_unreachable("Unexpected instr type to insert");
21739   case X86::TAILJMPd64:
21740   case X86::TAILJMPr64:
21741   case X86::TAILJMPm64:
21742   case X86::TAILJMPd64_REX:
21743   case X86::TAILJMPr64_REX:
21744   case X86::TAILJMPm64_REX:
21745     llvm_unreachable("TAILJMP64 would not be touched here.");
21746   case X86::TCRETURNdi64:
21747   case X86::TCRETURNri64:
21748   case X86::TCRETURNmi64:
21749     return BB;
21750   case X86::WIN_ALLOCA:
21751     return EmitLoweredWinAlloca(MI, BB);
21752   case X86::SEG_ALLOCA_32:
21753   case X86::SEG_ALLOCA_64:
21754     return EmitLoweredSegAlloca(MI, BB);
21755   case X86::TLSCall_32:
21756   case X86::TLSCall_64:
21757     return EmitLoweredTLSCall(MI, BB);
21758   case X86::CMOV_FR32:
21759   case X86::CMOV_FR64:
21760   case X86::CMOV_GR8:
21761   case X86::CMOV_GR16:
21762   case X86::CMOV_GR32:
21763   case X86::CMOV_RFP32:
21764   case X86::CMOV_RFP64:
21765   case X86::CMOV_RFP80:
21766   case X86::CMOV_V2F64:
21767   case X86::CMOV_V2I64:
21768   case X86::CMOV_V4F32:
21769   case X86::CMOV_V4F64:
21770   case X86::CMOV_V4I64:
21771   case X86::CMOV_V16F32:
21772   case X86::CMOV_V8F32:
21773   case X86::CMOV_V8F64:
21774   case X86::CMOV_V8I64:
21775   case X86::CMOV_V8I1:
21776   case X86::CMOV_V16I1:
21777   case X86::CMOV_V32I1:
21778   case X86::CMOV_V64I1:
21779     return EmitLoweredSelect(MI, BB);
21780
21781   case X86::RELEASE_FADD32mr:
21782   case X86::RELEASE_FADD64mr:
21783     return EmitLoweredAtomicFP(MI, BB);
21784
21785   case X86::FP32_TO_INT16_IN_MEM:
21786   case X86::FP32_TO_INT32_IN_MEM:
21787   case X86::FP32_TO_INT64_IN_MEM:
21788   case X86::FP64_TO_INT16_IN_MEM:
21789   case X86::FP64_TO_INT32_IN_MEM:
21790   case X86::FP64_TO_INT64_IN_MEM:
21791   case X86::FP80_TO_INT16_IN_MEM:
21792   case X86::FP80_TO_INT32_IN_MEM:
21793   case X86::FP80_TO_INT64_IN_MEM: {
21794     MachineFunction *F = BB->getParent();
21795     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21796     DebugLoc DL = MI->getDebugLoc();
21797
21798     // Change the floating point control register to use "round towards zero"
21799     // mode when truncating to an integer value.
21800     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21801     addFrameReference(BuildMI(*BB, MI, DL,
21802                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21803
21804     // Load the old value of the high byte of the control word...
21805     unsigned OldCW =
21806       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21807     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21808                       CWFrameIdx);
21809
21810     // Set the high part to be round to zero...
21811     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21812       .addImm(0xC7F);
21813
21814     // Reload the modified control word now...
21815     addFrameReference(BuildMI(*BB, MI, DL,
21816                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21817
21818     // Restore the memory image of control word to original value
21819     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21820       .addReg(OldCW);
21821
21822     // Get the X86 opcode to use.
21823     unsigned Opc;
21824     switch (MI->getOpcode()) {
21825     default: llvm_unreachable("illegal opcode!");
21826     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21827     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21828     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21829     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21830     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21831     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21832     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21833     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21834     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21835     }
21836
21837     X86AddressMode AM;
21838     MachineOperand &Op = MI->getOperand(0);
21839     if (Op.isReg()) {
21840       AM.BaseType = X86AddressMode::RegBase;
21841       AM.Base.Reg = Op.getReg();
21842     } else {
21843       AM.BaseType = X86AddressMode::FrameIndexBase;
21844       AM.Base.FrameIndex = Op.getIndex();
21845     }
21846     Op = MI->getOperand(1);
21847     if (Op.isImm())
21848       AM.Scale = Op.getImm();
21849     Op = MI->getOperand(2);
21850     if (Op.isImm())
21851       AM.IndexReg = Op.getImm();
21852     Op = MI->getOperand(3);
21853     if (Op.isGlobal()) {
21854       AM.GV = Op.getGlobal();
21855     } else {
21856       AM.Disp = Op.getImm();
21857     }
21858     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21859                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21860
21861     // Reload the original control word now.
21862     addFrameReference(BuildMI(*BB, MI, DL,
21863                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21864
21865     MI->eraseFromParent();   // The pseudo instruction is gone now.
21866     return BB;
21867   }
21868     // String/text processing lowering.
21869   case X86::PCMPISTRM128REG:
21870   case X86::VPCMPISTRM128REG:
21871   case X86::PCMPISTRM128MEM:
21872   case X86::VPCMPISTRM128MEM:
21873   case X86::PCMPESTRM128REG:
21874   case X86::VPCMPESTRM128REG:
21875   case X86::PCMPESTRM128MEM:
21876   case X86::VPCMPESTRM128MEM:
21877     assert(Subtarget->hasSSE42() &&
21878            "Target must have SSE4.2 or AVX features enabled");
21879     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21880
21881   // String/text processing lowering.
21882   case X86::PCMPISTRIREG:
21883   case X86::VPCMPISTRIREG:
21884   case X86::PCMPISTRIMEM:
21885   case X86::VPCMPISTRIMEM:
21886   case X86::PCMPESTRIREG:
21887   case X86::VPCMPESTRIREG:
21888   case X86::PCMPESTRIMEM:
21889   case X86::VPCMPESTRIMEM:
21890     assert(Subtarget->hasSSE42() &&
21891            "Target must have SSE4.2 or AVX features enabled");
21892     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21893
21894   // Thread synchronization.
21895   case X86::MONITOR:
21896     return EmitMonitor(MI, BB, Subtarget);
21897
21898   // xbegin
21899   case X86::XBEGIN:
21900     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21901
21902   case X86::VASTART_SAVE_XMM_REGS:
21903     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21904
21905   case X86::VAARG_64:
21906     return EmitVAARG64WithCustomInserter(MI, BB);
21907
21908   case X86::EH_SjLj_SetJmp32:
21909   case X86::EH_SjLj_SetJmp64:
21910     return emitEHSjLjSetJmp(MI, BB);
21911
21912   case X86::EH_SjLj_LongJmp32:
21913   case X86::EH_SjLj_LongJmp64:
21914     return emitEHSjLjLongJmp(MI, BB);
21915
21916   case TargetOpcode::STATEPOINT:
21917     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21918     // this point in the process.  We diverge later.
21919     return emitPatchPoint(MI, BB);
21920
21921   case TargetOpcode::STACKMAP:
21922   case TargetOpcode::PATCHPOINT:
21923     return emitPatchPoint(MI, BB);
21924
21925   case X86::VFMADDPDr213r:
21926   case X86::VFMADDPSr213r:
21927   case X86::VFMADDSDr213r:
21928   case X86::VFMADDSSr213r:
21929   case X86::VFMSUBPDr213r:
21930   case X86::VFMSUBPSr213r:
21931   case X86::VFMSUBSDr213r:
21932   case X86::VFMSUBSSr213r:
21933   case X86::VFNMADDPDr213r:
21934   case X86::VFNMADDPSr213r:
21935   case X86::VFNMADDSDr213r:
21936   case X86::VFNMADDSSr213r:
21937   case X86::VFNMSUBPDr213r:
21938   case X86::VFNMSUBPSr213r:
21939   case X86::VFNMSUBSDr213r:
21940   case X86::VFNMSUBSSr213r:
21941   case X86::VFMADDSUBPDr213r:
21942   case X86::VFMADDSUBPSr213r:
21943   case X86::VFMSUBADDPDr213r:
21944   case X86::VFMSUBADDPSr213r:
21945   case X86::VFMADDPDr213rY:
21946   case X86::VFMADDPSr213rY:
21947   case X86::VFMSUBPDr213rY:
21948   case X86::VFMSUBPSr213rY:
21949   case X86::VFNMADDPDr213rY:
21950   case X86::VFNMADDPSr213rY:
21951   case X86::VFNMSUBPDr213rY:
21952   case X86::VFNMSUBPSr213rY:
21953   case X86::VFMADDSUBPDr213rY:
21954   case X86::VFMADDSUBPSr213rY:
21955   case X86::VFMSUBADDPDr213rY:
21956   case X86::VFMSUBADDPSr213rY:
21957     return emitFMA3Instr(MI, BB);
21958   }
21959 }
21960
21961 //===----------------------------------------------------------------------===//
21962 //                           X86 Optimization Hooks
21963 //===----------------------------------------------------------------------===//
21964
21965 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21966                                                       APInt &KnownZero,
21967                                                       APInt &KnownOne,
21968                                                       const SelectionDAG &DAG,
21969                                                       unsigned Depth) const {
21970   unsigned BitWidth = KnownZero.getBitWidth();
21971   unsigned Opc = Op.getOpcode();
21972   assert((Opc >= ISD::BUILTIN_OP_END ||
21973           Opc == ISD::INTRINSIC_WO_CHAIN ||
21974           Opc == ISD::INTRINSIC_W_CHAIN ||
21975           Opc == ISD::INTRINSIC_VOID) &&
21976          "Should use MaskedValueIsZero if you don't know whether Op"
21977          " is a target node!");
21978
21979   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21980   switch (Opc) {
21981   default: break;
21982   case X86ISD::ADD:
21983   case X86ISD::SUB:
21984   case X86ISD::ADC:
21985   case X86ISD::SBB:
21986   case X86ISD::SMUL:
21987   case X86ISD::UMUL:
21988   case X86ISD::INC:
21989   case X86ISD::DEC:
21990   case X86ISD::OR:
21991   case X86ISD::XOR:
21992   case X86ISD::AND:
21993     // These nodes' second result is a boolean.
21994     if (Op.getResNo() == 0)
21995       break;
21996     // Fallthrough
21997   case X86ISD::SETCC:
21998     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21999     break;
22000   case ISD::INTRINSIC_WO_CHAIN: {
22001     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22002     unsigned NumLoBits = 0;
22003     switch (IntId) {
22004     default: break;
22005     case Intrinsic::x86_sse_movmsk_ps:
22006     case Intrinsic::x86_avx_movmsk_ps_256:
22007     case Intrinsic::x86_sse2_movmsk_pd:
22008     case Intrinsic::x86_avx_movmsk_pd_256:
22009     case Intrinsic::x86_mmx_pmovmskb:
22010     case Intrinsic::x86_sse2_pmovmskb_128:
22011     case Intrinsic::x86_avx2_pmovmskb: {
22012       // High bits of movmskp{s|d}, pmovmskb are known zero.
22013       switch (IntId) {
22014         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22015         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22016         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22017         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22018         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22019         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22020         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22021         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22022       }
22023       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22024       break;
22025     }
22026     }
22027     break;
22028   }
22029   }
22030 }
22031
22032 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22033   SDValue Op,
22034   const SelectionDAG &,
22035   unsigned Depth) const {
22036   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22037   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22038     return Op.getValueType().getScalarType().getSizeInBits();
22039
22040   // Fallback case.
22041   return 1;
22042 }
22043
22044 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22045 /// node is a GlobalAddress + offset.
22046 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22047                                        const GlobalValue* &GA,
22048                                        int64_t &Offset) const {
22049   if (N->getOpcode() == X86ISD::Wrapper) {
22050     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22051       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22052       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22053       return true;
22054     }
22055   }
22056   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22057 }
22058
22059 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22060 /// same as extracting the high 128-bit part of 256-bit vector and then
22061 /// inserting the result into the low part of a new 256-bit vector
22062 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22063   EVT VT = SVOp->getValueType(0);
22064   unsigned NumElems = VT.getVectorNumElements();
22065
22066   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22067   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22068     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22069         SVOp->getMaskElt(j) >= 0)
22070       return false;
22071
22072   return true;
22073 }
22074
22075 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22076 /// same as extracting the low 128-bit part of 256-bit vector and then
22077 /// inserting the result into the high part of a new 256-bit vector
22078 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22079   EVT VT = SVOp->getValueType(0);
22080   unsigned NumElems = VT.getVectorNumElements();
22081
22082   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22083   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22084     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22085         SVOp->getMaskElt(j) >= 0)
22086       return false;
22087
22088   return true;
22089 }
22090
22091 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22092 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22093                                         TargetLowering::DAGCombinerInfo &DCI,
22094                                         const X86Subtarget* Subtarget) {
22095   SDLoc dl(N);
22096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22097   SDValue V1 = SVOp->getOperand(0);
22098   SDValue V2 = SVOp->getOperand(1);
22099   EVT VT = SVOp->getValueType(0);
22100   unsigned NumElems = VT.getVectorNumElements();
22101
22102   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22103       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22104     //
22105     //                   0,0,0,...
22106     //                      |
22107     //    V      UNDEF    BUILD_VECTOR    UNDEF
22108     //     \      /           \           /
22109     //  CONCAT_VECTOR         CONCAT_VECTOR
22110     //         \                  /
22111     //          \                /
22112     //          RESULT: V + zero extended
22113     //
22114     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22115         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22116         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22117       return SDValue();
22118
22119     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22120       return SDValue();
22121
22122     // To match the shuffle mask, the first half of the mask should
22123     // be exactly the first vector, and all the rest a splat with the
22124     // first element of the second one.
22125     for (unsigned i = 0; i != NumElems/2; ++i)
22126       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22127           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22128         return SDValue();
22129
22130     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22131     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22132       if (Ld->hasNUsesOfValue(1, 0)) {
22133         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22134         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22135         SDValue ResNode =
22136           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22137                                   Ld->getMemoryVT(),
22138                                   Ld->getPointerInfo(),
22139                                   Ld->getAlignment(),
22140                                   false/*isVolatile*/, true/*ReadMem*/,
22141                                   false/*WriteMem*/);
22142
22143         // Make sure the newly-created LOAD is in the same position as Ld in
22144         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22145         // and update uses of Ld's output chain to use the TokenFactor.
22146         if (Ld->hasAnyUseOfValue(1)) {
22147           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22148                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22149           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22150           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22151                                  SDValue(ResNode.getNode(), 1));
22152         }
22153
22154         return DAG.getBitcast(VT, ResNode);
22155       }
22156     }
22157
22158     // Emit a zeroed vector and insert the desired subvector on its
22159     // first half.
22160     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22161     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22162     return DCI.CombineTo(N, InsV);
22163   }
22164
22165   //===--------------------------------------------------------------------===//
22166   // Combine some shuffles into subvector extracts and inserts:
22167   //
22168
22169   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22170   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22171     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22172     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22173     return DCI.CombineTo(N, InsV);
22174   }
22175
22176   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22177   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22178     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22179     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22180     return DCI.CombineTo(N, InsV);
22181   }
22182
22183   return SDValue();
22184 }
22185
22186 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22187 /// possible.
22188 ///
22189 /// This is the leaf of the recursive combinine below. When we have found some
22190 /// chain of single-use x86 shuffle instructions and accumulated the combined
22191 /// shuffle mask represented by them, this will try to pattern match that mask
22192 /// into either a single instruction if there is a special purpose instruction
22193 /// for this operation, or into a PSHUFB instruction which is a fully general
22194 /// instruction but should only be used to replace chains over a certain depth.
22195 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22196                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22197                                    TargetLowering::DAGCombinerInfo &DCI,
22198                                    const X86Subtarget *Subtarget) {
22199   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22200
22201   // Find the operand that enters the chain. Note that multiple uses are OK
22202   // here, we're not going to remove the operand we find.
22203   SDValue Input = Op.getOperand(0);
22204   while (Input.getOpcode() == ISD::BITCAST)
22205     Input = Input.getOperand(0);
22206
22207   MVT VT = Input.getSimpleValueType();
22208   MVT RootVT = Root.getSimpleValueType();
22209   SDLoc DL(Root);
22210
22211   if (Mask.size() == 1) {
22212     int Index = Mask[0];
22213     assert((Index >= 0 || Index == SM_SentinelUndef ||
22214             Index == SM_SentinelZero) &&
22215            "Invalid shuffle index found!");
22216
22217     // We may end up with an accumulated mask of size 1 as a result of
22218     // widening of shuffle operands (see function canWidenShuffleElements).
22219     // If the only shuffle index is equal to SM_SentinelZero then propagate
22220     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22221     // mask, and therefore the entire chain of shuffles can be folded away.
22222     if (Index == SM_SentinelZero)
22223       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22224     else
22225       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22226                     /*AddTo*/ true);
22227     return true;
22228   }
22229
22230   // Use the float domain if the operand type is a floating point type.
22231   bool FloatDomain = VT.isFloatingPoint();
22232
22233   // For floating point shuffles, we don't have free copies in the shuffle
22234   // instructions or the ability to load as part of the instruction, so
22235   // canonicalize their shuffles to UNPCK or MOV variants.
22236   //
22237   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22238   // vectors because it can have a load folded into it that UNPCK cannot. This
22239   // doesn't preclude something switching to the shorter encoding post-RA.
22240   //
22241   // FIXME: Should teach these routines about AVX vector widths.
22242   if (FloatDomain && VT.getSizeInBits() == 128) {
22243     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22244       bool Lo = Mask.equals({0, 0});
22245       unsigned Shuffle;
22246       MVT ShuffleVT;
22247       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22248       // is no slower than UNPCKLPD but has the option to fold the input operand
22249       // into even an unaligned memory load.
22250       if (Lo && Subtarget->hasSSE3()) {
22251         Shuffle = X86ISD::MOVDDUP;
22252         ShuffleVT = MVT::v2f64;
22253       } else {
22254         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22255         // than the UNPCK variants.
22256         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22257         ShuffleVT = MVT::v4f32;
22258       }
22259       if (Depth == 1 && Root->getOpcode() == Shuffle)
22260         return false; // Nothing to do!
22261       Op = DAG.getBitcast(ShuffleVT, Input);
22262       DCI.AddToWorklist(Op.getNode());
22263       if (Shuffle == X86ISD::MOVDDUP)
22264         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22265       else
22266         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22267       DCI.AddToWorklist(Op.getNode());
22268       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22269                     /*AddTo*/ true);
22270       return true;
22271     }
22272     if (Subtarget->hasSSE3() &&
22273         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22274       bool Lo = Mask.equals({0, 0, 2, 2});
22275       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22276       MVT ShuffleVT = MVT::v4f32;
22277       if (Depth == 1 && Root->getOpcode() == Shuffle)
22278         return false; // Nothing to do!
22279       Op = DAG.getBitcast(ShuffleVT, Input);
22280       DCI.AddToWorklist(Op.getNode());
22281       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22282       DCI.AddToWorklist(Op.getNode());
22283       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22284                     /*AddTo*/ true);
22285       return true;
22286     }
22287     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22288       bool Lo = Mask.equals({0, 0, 1, 1});
22289       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22290       MVT ShuffleVT = MVT::v4f32;
22291       if (Depth == 1 && Root->getOpcode() == Shuffle)
22292         return false; // Nothing to do!
22293       Op = DAG.getBitcast(ShuffleVT, Input);
22294       DCI.AddToWorklist(Op.getNode());
22295       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22296       DCI.AddToWorklist(Op.getNode());
22297       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22298                     /*AddTo*/ true);
22299       return true;
22300     }
22301   }
22302
22303   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22304   // variants as none of these have single-instruction variants that are
22305   // superior to the UNPCK formulation.
22306   if (!FloatDomain && VT.getSizeInBits() == 128 &&
22307       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22308        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22309        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22310        Mask.equals(
22311            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22312     bool Lo = Mask[0] == 0;
22313     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22314     if (Depth == 1 && Root->getOpcode() == Shuffle)
22315       return false; // Nothing to do!
22316     MVT ShuffleVT;
22317     switch (Mask.size()) {
22318     case 8:
22319       ShuffleVT = MVT::v8i16;
22320       break;
22321     case 16:
22322       ShuffleVT = MVT::v16i8;
22323       break;
22324     default:
22325       llvm_unreachable("Impossible mask size!");
22326     };
22327     Op = DAG.getBitcast(ShuffleVT, Input);
22328     DCI.AddToWorklist(Op.getNode());
22329     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22330     DCI.AddToWorklist(Op.getNode());
22331     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22332                   /*AddTo*/ true);
22333     return true;
22334   }
22335
22336   // Don't try to re-form single instruction chains under any circumstances now
22337   // that we've done encoding canonicalization for them.
22338   if (Depth < 2)
22339     return false;
22340
22341   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22342   // can replace them with a single PSHUFB instruction profitably. Intel's
22343   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22344   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22345   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22346     SmallVector<SDValue, 16> PSHUFBMask;
22347     int NumBytes = VT.getSizeInBits() / 8;
22348     int Ratio = NumBytes / Mask.size();
22349     for (int i = 0; i < NumBytes; ++i) {
22350       if (Mask[i / Ratio] == SM_SentinelUndef) {
22351         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22352         continue;
22353       }
22354       int M = Mask[i / Ratio] != SM_SentinelZero
22355                   ? Ratio * Mask[i / Ratio] + i % Ratio
22356                   : 255;
22357       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22358     }
22359     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22360     Op = DAG.getBitcast(ByteVT, Input);
22361     DCI.AddToWorklist(Op.getNode());
22362     SDValue PSHUFBMaskOp =
22363         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22364     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22365     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22366     DCI.AddToWorklist(Op.getNode());
22367     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22368                   /*AddTo*/ true);
22369     return true;
22370   }
22371
22372   // Failed to find any combines.
22373   return false;
22374 }
22375
22376 /// \brief Fully generic combining of x86 shuffle instructions.
22377 ///
22378 /// This should be the last combine run over the x86 shuffle instructions. Once
22379 /// they have been fully optimized, this will recursively consider all chains
22380 /// of single-use shuffle instructions, build a generic model of the cumulative
22381 /// shuffle operation, and check for simpler instructions which implement this
22382 /// operation. We use this primarily for two purposes:
22383 ///
22384 /// 1) Collapse generic shuffles to specialized single instructions when
22385 ///    equivalent. In most cases, this is just an encoding size win, but
22386 ///    sometimes we will collapse multiple generic shuffles into a single
22387 ///    special-purpose shuffle.
22388 /// 2) Look for sequences of shuffle instructions with 3 or more total
22389 ///    instructions, and replace them with the slightly more expensive SSSE3
22390 ///    PSHUFB instruction if available. We do this as the last combining step
22391 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22392 ///    a suitable short sequence of other instructions. The PHUFB will either
22393 ///    use a register or have to read from memory and so is slightly (but only
22394 ///    slightly) more expensive than the other shuffle instructions.
22395 ///
22396 /// Because this is inherently a quadratic operation (for each shuffle in
22397 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22398 /// This should never be an issue in practice as the shuffle lowering doesn't
22399 /// produce sequences of more than 8 instructions.
22400 ///
22401 /// FIXME: We will currently miss some cases where the redundant shuffling
22402 /// would simplify under the threshold for PSHUFB formation because of
22403 /// combine-ordering. To fix this, we should do the redundant instruction
22404 /// combining in this recursive walk.
22405 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22406                                           ArrayRef<int> RootMask,
22407                                           int Depth, bool HasPSHUFB,
22408                                           SelectionDAG &DAG,
22409                                           TargetLowering::DAGCombinerInfo &DCI,
22410                                           const X86Subtarget *Subtarget) {
22411   // Bound the depth of our recursive combine because this is ultimately
22412   // quadratic in nature.
22413   if (Depth > 8)
22414     return false;
22415
22416   // Directly rip through bitcasts to find the underlying operand.
22417   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22418     Op = Op.getOperand(0);
22419
22420   MVT VT = Op.getSimpleValueType();
22421   if (!VT.isVector())
22422     return false; // Bail if we hit a non-vector.
22423
22424   assert(Root.getSimpleValueType().isVector() &&
22425          "Shuffles operate on vector types!");
22426   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22427          "Can only combine shuffles of the same vector register size.");
22428
22429   if (!isTargetShuffle(Op.getOpcode()))
22430     return false;
22431   SmallVector<int, 16> OpMask;
22432   bool IsUnary;
22433   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22434   // We only can combine unary shuffles which we can decode the mask for.
22435   if (!HaveMask || !IsUnary)
22436     return false;
22437
22438   assert(VT.getVectorNumElements() == OpMask.size() &&
22439          "Different mask size from vector size!");
22440   assert(((RootMask.size() > OpMask.size() &&
22441            RootMask.size() % OpMask.size() == 0) ||
22442           (OpMask.size() > RootMask.size() &&
22443            OpMask.size() % RootMask.size() == 0) ||
22444           OpMask.size() == RootMask.size()) &&
22445          "The smaller number of elements must divide the larger.");
22446   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22447   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22448   assert(((RootRatio == 1 && OpRatio == 1) ||
22449           (RootRatio == 1) != (OpRatio == 1)) &&
22450          "Must not have a ratio for both incoming and op masks!");
22451
22452   SmallVector<int, 16> Mask;
22453   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22454
22455   // Merge this shuffle operation's mask into our accumulated mask. Note that
22456   // this shuffle's mask will be the first applied to the input, followed by the
22457   // root mask to get us all the way to the root value arrangement. The reason
22458   // for this order is that we are recursing up the operation chain.
22459   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22460     int RootIdx = i / RootRatio;
22461     if (RootMask[RootIdx] < 0) {
22462       // This is a zero or undef lane, we're done.
22463       Mask.push_back(RootMask[RootIdx]);
22464       continue;
22465     }
22466
22467     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22468     int OpIdx = RootMaskedIdx / OpRatio;
22469     if (OpMask[OpIdx] < 0) {
22470       // The incoming lanes are zero or undef, it doesn't matter which ones we
22471       // are using.
22472       Mask.push_back(OpMask[OpIdx]);
22473       continue;
22474     }
22475
22476     // Ok, we have non-zero lanes, map them through.
22477     Mask.push_back(OpMask[OpIdx] * OpRatio +
22478                    RootMaskedIdx % OpRatio);
22479   }
22480
22481   // See if we can recurse into the operand to combine more things.
22482   switch (Op.getOpcode()) {
22483   case X86ISD::PSHUFB:
22484     HasPSHUFB = true;
22485   case X86ISD::PSHUFD:
22486   case X86ISD::PSHUFHW:
22487   case X86ISD::PSHUFLW:
22488     if (Op.getOperand(0).hasOneUse() &&
22489         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22490                                       HasPSHUFB, DAG, DCI, Subtarget))
22491       return true;
22492     break;
22493
22494   case X86ISD::UNPCKL:
22495   case X86ISD::UNPCKH:
22496     assert(Op.getOperand(0) == Op.getOperand(1) &&
22497            "We only combine unary shuffles!");
22498     // We can't check for single use, we have to check that this shuffle is the
22499     // only user.
22500     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22501         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22502                                       HasPSHUFB, DAG, DCI, Subtarget))
22503       return true;
22504     break;
22505   }
22506
22507   // Minor canonicalization of the accumulated shuffle mask to make it easier
22508   // to match below. All this does is detect masks with squential pairs of
22509   // elements, and shrink them to the half-width mask. It does this in a loop
22510   // so it will reduce the size of the mask to the minimal width mask which
22511   // performs an equivalent shuffle.
22512   SmallVector<int, 16> WidenedMask;
22513   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22514     Mask = std::move(WidenedMask);
22515     WidenedMask.clear();
22516   }
22517
22518   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22519                                 Subtarget);
22520 }
22521
22522 /// \brief Get the PSHUF-style mask from PSHUF node.
22523 ///
22524 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22525 /// PSHUF-style masks that can be reused with such instructions.
22526 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22527   MVT VT = N.getSimpleValueType();
22528   SmallVector<int, 4> Mask;
22529   bool IsUnary;
22530   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22531   (void)HaveMask;
22532   assert(HaveMask);
22533
22534   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22535   // matter. Check that the upper masks are repeats and remove them.
22536   if (VT.getSizeInBits() > 128) {
22537     int LaneElts = 128 / VT.getScalarSizeInBits();
22538 #ifndef NDEBUG
22539     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22540       for (int j = 0; j < LaneElts; ++j)
22541         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22542                "Mask doesn't repeat in high 128-bit lanes!");
22543 #endif
22544     Mask.resize(LaneElts);
22545   }
22546
22547   switch (N.getOpcode()) {
22548   case X86ISD::PSHUFD:
22549     return Mask;
22550   case X86ISD::PSHUFLW:
22551     Mask.resize(4);
22552     return Mask;
22553   case X86ISD::PSHUFHW:
22554     Mask.erase(Mask.begin(), Mask.begin() + 4);
22555     for (int &M : Mask)
22556       M -= 4;
22557     return Mask;
22558   default:
22559     llvm_unreachable("No valid shuffle instruction found!");
22560   }
22561 }
22562
22563 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22564 ///
22565 /// We walk up the chain and look for a combinable shuffle, skipping over
22566 /// shuffles that we could hoist this shuffle's transformation past without
22567 /// altering anything.
22568 static SDValue
22569 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22570                              SelectionDAG &DAG,
22571                              TargetLowering::DAGCombinerInfo &DCI) {
22572   assert(N.getOpcode() == X86ISD::PSHUFD &&
22573          "Called with something other than an x86 128-bit half shuffle!");
22574   SDLoc DL(N);
22575
22576   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22577   // of the shuffles in the chain so that we can form a fresh chain to replace
22578   // this one.
22579   SmallVector<SDValue, 8> Chain;
22580   SDValue V = N.getOperand(0);
22581   for (; V.hasOneUse(); V = V.getOperand(0)) {
22582     switch (V.getOpcode()) {
22583     default:
22584       return SDValue(); // Nothing combined!
22585
22586     case ISD::BITCAST:
22587       // Skip bitcasts as we always know the type for the target specific
22588       // instructions.
22589       continue;
22590
22591     case X86ISD::PSHUFD:
22592       // Found another dword shuffle.
22593       break;
22594
22595     case X86ISD::PSHUFLW:
22596       // Check that the low words (being shuffled) are the identity in the
22597       // dword shuffle, and the high words are self-contained.
22598       if (Mask[0] != 0 || Mask[1] != 1 ||
22599           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22600         return SDValue();
22601
22602       Chain.push_back(V);
22603       continue;
22604
22605     case X86ISD::PSHUFHW:
22606       // Check that the high words (being shuffled) are the identity in the
22607       // dword shuffle, and the low words are self-contained.
22608       if (Mask[2] != 2 || Mask[3] != 3 ||
22609           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22610         return SDValue();
22611
22612       Chain.push_back(V);
22613       continue;
22614
22615     case X86ISD::UNPCKL:
22616     case X86ISD::UNPCKH:
22617       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22618       // shuffle into a preceding word shuffle.
22619       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22620           V.getSimpleValueType().getScalarType() != MVT::i16)
22621         return SDValue();
22622
22623       // Search for a half-shuffle which we can combine with.
22624       unsigned CombineOp =
22625           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22626       if (V.getOperand(0) != V.getOperand(1) ||
22627           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22628         return SDValue();
22629       Chain.push_back(V);
22630       V = V.getOperand(0);
22631       do {
22632         switch (V.getOpcode()) {
22633         default:
22634           return SDValue(); // Nothing to combine.
22635
22636         case X86ISD::PSHUFLW:
22637         case X86ISD::PSHUFHW:
22638           if (V.getOpcode() == CombineOp)
22639             break;
22640
22641           Chain.push_back(V);
22642
22643           // Fallthrough!
22644         case ISD::BITCAST:
22645           V = V.getOperand(0);
22646           continue;
22647         }
22648         break;
22649       } while (V.hasOneUse());
22650       break;
22651     }
22652     // Break out of the loop if we break out of the switch.
22653     break;
22654   }
22655
22656   if (!V.hasOneUse())
22657     // We fell out of the loop without finding a viable combining instruction.
22658     return SDValue();
22659
22660   // Merge this node's mask and our incoming mask.
22661   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22662   for (int &M : Mask)
22663     M = VMask[M];
22664   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22665                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22666
22667   // Rebuild the chain around this new shuffle.
22668   while (!Chain.empty()) {
22669     SDValue W = Chain.pop_back_val();
22670
22671     if (V.getValueType() != W.getOperand(0).getValueType())
22672       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22673
22674     switch (W.getOpcode()) {
22675     default:
22676       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22677
22678     case X86ISD::UNPCKL:
22679     case X86ISD::UNPCKH:
22680       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22681       break;
22682
22683     case X86ISD::PSHUFD:
22684     case X86ISD::PSHUFLW:
22685     case X86ISD::PSHUFHW:
22686       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22687       break;
22688     }
22689   }
22690   if (V.getValueType() != N.getValueType())
22691     V = DAG.getBitcast(N.getValueType(), V);
22692
22693   // Return the new chain to replace N.
22694   return V;
22695 }
22696
22697 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22698 /// pshufhw.
22699 ///
22700 /// We walk up the chain, skipping shuffles of the other half and looking
22701 /// through shuffles which switch halves trying to find a shuffle of the same
22702 /// pair of dwords.
22703 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22704                                         SelectionDAG &DAG,
22705                                         TargetLowering::DAGCombinerInfo &DCI) {
22706   assert(
22707       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22708       "Called with something other than an x86 128-bit half shuffle!");
22709   SDLoc DL(N);
22710   unsigned CombineOpcode = N.getOpcode();
22711
22712   // Walk up a single-use chain looking for a combinable shuffle.
22713   SDValue V = N.getOperand(0);
22714   for (; V.hasOneUse(); V = V.getOperand(0)) {
22715     switch (V.getOpcode()) {
22716     default:
22717       return false; // Nothing combined!
22718
22719     case ISD::BITCAST:
22720       // Skip bitcasts as we always know the type for the target specific
22721       // instructions.
22722       continue;
22723
22724     case X86ISD::PSHUFLW:
22725     case X86ISD::PSHUFHW:
22726       if (V.getOpcode() == CombineOpcode)
22727         break;
22728
22729       // Other-half shuffles are no-ops.
22730       continue;
22731     }
22732     // Break out of the loop if we break out of the switch.
22733     break;
22734   }
22735
22736   if (!V.hasOneUse())
22737     // We fell out of the loop without finding a viable combining instruction.
22738     return false;
22739
22740   // Combine away the bottom node as its shuffle will be accumulated into
22741   // a preceding shuffle.
22742   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22743
22744   // Record the old value.
22745   SDValue Old = V;
22746
22747   // Merge this node's mask and our incoming mask (adjusted to account for all
22748   // the pshufd instructions encountered).
22749   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22750   for (int &M : Mask)
22751     M = VMask[M];
22752   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22753                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22754
22755   // Check that the shuffles didn't cancel each other out. If not, we need to
22756   // combine to the new one.
22757   if (Old != V)
22758     // Replace the combinable shuffle with the combined one, updating all users
22759     // so that we re-evaluate the chain here.
22760     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22761
22762   return true;
22763 }
22764
22765 /// \brief Try to combine x86 target specific shuffles.
22766 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22767                                            TargetLowering::DAGCombinerInfo &DCI,
22768                                            const X86Subtarget *Subtarget) {
22769   SDLoc DL(N);
22770   MVT VT = N.getSimpleValueType();
22771   SmallVector<int, 4> Mask;
22772
22773   switch (N.getOpcode()) {
22774   case X86ISD::PSHUFD:
22775   case X86ISD::PSHUFLW:
22776   case X86ISD::PSHUFHW:
22777     Mask = getPSHUFShuffleMask(N);
22778     assert(Mask.size() == 4);
22779     break;
22780   default:
22781     return SDValue();
22782   }
22783
22784   // Nuke no-op shuffles that show up after combining.
22785   if (isNoopShuffleMask(Mask))
22786     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22787
22788   // Look for simplifications involving one or two shuffle instructions.
22789   SDValue V = N.getOperand(0);
22790   switch (N.getOpcode()) {
22791   default:
22792     break;
22793   case X86ISD::PSHUFLW:
22794   case X86ISD::PSHUFHW:
22795     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22796
22797     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22798       return SDValue(); // We combined away this shuffle, so we're done.
22799
22800     // See if this reduces to a PSHUFD which is no more expensive and can
22801     // combine with more operations. Note that it has to at least flip the
22802     // dwords as otherwise it would have been removed as a no-op.
22803     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22804       int DMask[] = {0, 1, 2, 3};
22805       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22806       DMask[DOffset + 0] = DOffset + 1;
22807       DMask[DOffset + 1] = DOffset + 0;
22808       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22809       V = DAG.getBitcast(DVT, V);
22810       DCI.AddToWorklist(V.getNode());
22811       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22812                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22813       DCI.AddToWorklist(V.getNode());
22814       return DAG.getBitcast(VT, V);
22815     }
22816
22817     // Look for shuffle patterns which can be implemented as a single unpack.
22818     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22819     // only works when we have a PSHUFD followed by two half-shuffles.
22820     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22821         (V.getOpcode() == X86ISD::PSHUFLW ||
22822          V.getOpcode() == X86ISD::PSHUFHW) &&
22823         V.getOpcode() != N.getOpcode() &&
22824         V.hasOneUse()) {
22825       SDValue D = V.getOperand(0);
22826       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22827         D = D.getOperand(0);
22828       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22829         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22830         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22831         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22832         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22833         int WordMask[8];
22834         for (int i = 0; i < 4; ++i) {
22835           WordMask[i + NOffset] = Mask[i] + NOffset;
22836           WordMask[i + VOffset] = VMask[i] + VOffset;
22837         }
22838         // Map the word mask through the DWord mask.
22839         int MappedMask[8];
22840         for (int i = 0; i < 8; ++i)
22841           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22842         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22843             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22844           // We can replace all three shuffles with an unpack.
22845           V = DAG.getBitcast(VT, D.getOperand(0));
22846           DCI.AddToWorklist(V.getNode());
22847           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22848                                                 : X86ISD::UNPCKH,
22849                              DL, VT, V, V);
22850         }
22851       }
22852     }
22853
22854     break;
22855
22856   case X86ISD::PSHUFD:
22857     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22858       return NewN;
22859
22860     break;
22861   }
22862
22863   return SDValue();
22864 }
22865
22866 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22867 ///
22868 /// We combine this directly on the abstract vector shuffle nodes so it is
22869 /// easier to generically match. We also insert dummy vector shuffle nodes for
22870 /// the operands which explicitly discard the lanes which are unused by this
22871 /// operation to try to flow through the rest of the combiner the fact that
22872 /// they're unused.
22873 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22874   SDLoc DL(N);
22875   EVT VT = N->getValueType(0);
22876
22877   // We only handle target-independent shuffles.
22878   // FIXME: It would be easy and harmless to use the target shuffle mask
22879   // extraction tool to support more.
22880   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22881     return SDValue();
22882
22883   auto *SVN = cast<ShuffleVectorSDNode>(N);
22884   ArrayRef<int> Mask = SVN->getMask();
22885   SDValue V1 = N->getOperand(0);
22886   SDValue V2 = N->getOperand(1);
22887
22888   // We require the first shuffle operand to be the SUB node, and the second to
22889   // be the ADD node.
22890   // FIXME: We should support the commuted patterns.
22891   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22892     return SDValue();
22893
22894   // If there are other uses of these operations we can't fold them.
22895   if (!V1->hasOneUse() || !V2->hasOneUse())
22896     return SDValue();
22897
22898   // Ensure that both operations have the same operands. Note that we can
22899   // commute the FADD operands.
22900   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22901   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22902       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22903     return SDValue();
22904
22905   // We're looking for blends between FADD and FSUB nodes. We insist on these
22906   // nodes being lined up in a specific expected pattern.
22907   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22908         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22909         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22910     return SDValue();
22911
22912   // Only specific types are legal at this point, assert so we notice if and
22913   // when these change.
22914   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22915           VT == MVT::v4f64) &&
22916          "Unknown vector type encountered!");
22917
22918   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22919 }
22920
22921 /// PerformShuffleCombine - Performs several different shuffle combines.
22922 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22923                                      TargetLowering::DAGCombinerInfo &DCI,
22924                                      const X86Subtarget *Subtarget) {
22925   SDLoc dl(N);
22926   SDValue N0 = N->getOperand(0);
22927   SDValue N1 = N->getOperand(1);
22928   EVT VT = N->getValueType(0);
22929
22930   // Don't create instructions with illegal types after legalize types has run.
22931   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22932   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22933     return SDValue();
22934
22935   // If we have legalized the vector types, look for blends of FADD and FSUB
22936   // nodes that we can fuse into an ADDSUB node.
22937   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22938     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22939       return AddSub;
22940
22941   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22942   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22943       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22944     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22945
22946   // During Type Legalization, when promoting illegal vector types,
22947   // the backend might introduce new shuffle dag nodes and bitcasts.
22948   //
22949   // This code performs the following transformation:
22950   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22951   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22952   //
22953   // We do this only if both the bitcast and the BINOP dag nodes have
22954   // one use. Also, perform this transformation only if the new binary
22955   // operation is legal. This is to avoid introducing dag nodes that
22956   // potentially need to be further expanded (or custom lowered) into a
22957   // less optimal sequence of dag nodes.
22958   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22959       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22960       N0.getOpcode() == ISD::BITCAST) {
22961     SDValue BC0 = N0.getOperand(0);
22962     EVT SVT = BC0.getValueType();
22963     unsigned Opcode = BC0.getOpcode();
22964     unsigned NumElts = VT.getVectorNumElements();
22965
22966     if (BC0.hasOneUse() && SVT.isVector() &&
22967         SVT.getVectorNumElements() * 2 == NumElts &&
22968         TLI.isOperationLegal(Opcode, VT)) {
22969       bool CanFold = false;
22970       switch (Opcode) {
22971       default : break;
22972       case ISD::ADD :
22973       case ISD::FADD :
22974       case ISD::SUB :
22975       case ISD::FSUB :
22976       case ISD::MUL :
22977       case ISD::FMUL :
22978         CanFold = true;
22979       }
22980
22981       unsigned SVTNumElts = SVT.getVectorNumElements();
22982       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22983       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22984         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22985       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22986         CanFold = SVOp->getMaskElt(i) < 0;
22987
22988       if (CanFold) {
22989         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22990         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22991         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22992         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22993       }
22994     }
22995   }
22996
22997   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22998   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22999   // consecutive, non-overlapping, and in the right order.
23000   SmallVector<SDValue, 16> Elts;
23001   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23002     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23003
23004   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23005     return LD;
23006
23007   if (isTargetShuffle(N->getOpcode())) {
23008     SDValue Shuffle =
23009         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23010     if (Shuffle.getNode())
23011       return Shuffle;
23012
23013     // Try recursively combining arbitrary sequences of x86 shuffle
23014     // instructions into higher-order shuffles. We do this after combining
23015     // specific PSHUF instruction sequences into their minimal form so that we
23016     // can evaluate how many specialized shuffle instructions are involved in
23017     // a particular chain.
23018     SmallVector<int, 1> NonceMask; // Just a placeholder.
23019     NonceMask.push_back(0);
23020     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23021                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23022                                       DCI, Subtarget))
23023       return SDValue(); // This routine will use CombineTo to replace N.
23024   }
23025
23026   return SDValue();
23027 }
23028
23029 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23030 /// specific shuffle of a load can be folded into a single element load.
23031 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23032 /// shuffles have been custom lowered so we need to handle those here.
23033 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23034                                          TargetLowering::DAGCombinerInfo &DCI) {
23035   if (DCI.isBeforeLegalizeOps())
23036     return SDValue();
23037
23038   SDValue InVec = N->getOperand(0);
23039   SDValue EltNo = N->getOperand(1);
23040
23041   if (!isa<ConstantSDNode>(EltNo))
23042     return SDValue();
23043
23044   EVT OriginalVT = InVec.getValueType();
23045
23046   if (InVec.getOpcode() == ISD::BITCAST) {
23047     // Don't duplicate a load with other uses.
23048     if (!InVec.hasOneUse())
23049       return SDValue();
23050     EVT BCVT = InVec.getOperand(0).getValueType();
23051     if (!BCVT.isVector() ||
23052         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23053       return SDValue();
23054     InVec = InVec.getOperand(0);
23055   }
23056
23057   EVT CurrentVT = InVec.getValueType();
23058
23059   if (!isTargetShuffle(InVec.getOpcode()))
23060     return SDValue();
23061
23062   // Don't duplicate a load with other uses.
23063   if (!InVec.hasOneUse())
23064     return SDValue();
23065
23066   SmallVector<int, 16> ShuffleMask;
23067   bool UnaryShuffle;
23068   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23069                             ShuffleMask, UnaryShuffle))
23070     return SDValue();
23071
23072   // Select the input vector, guarding against out of range extract vector.
23073   unsigned NumElems = CurrentVT.getVectorNumElements();
23074   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23075   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23076   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23077                                          : InVec.getOperand(1);
23078
23079   // If inputs to shuffle are the same for both ops, then allow 2 uses
23080   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23081                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23082
23083   if (LdNode.getOpcode() == ISD::BITCAST) {
23084     // Don't duplicate a load with other uses.
23085     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23086       return SDValue();
23087
23088     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23089     LdNode = LdNode.getOperand(0);
23090   }
23091
23092   if (!ISD::isNormalLoad(LdNode.getNode()))
23093     return SDValue();
23094
23095   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23096
23097   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23098     return SDValue();
23099
23100   EVT EltVT = N->getValueType(0);
23101   // If there's a bitcast before the shuffle, check if the load type and
23102   // alignment is valid.
23103   unsigned Align = LN0->getAlignment();
23104   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23105   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23106       EltVT.getTypeForEVT(*DAG.getContext()));
23107
23108   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23109     return SDValue();
23110
23111   // All checks match so transform back to vector_shuffle so that DAG combiner
23112   // can finish the job
23113   SDLoc dl(N);
23114
23115   // Create shuffle node taking into account the case that its a unary shuffle
23116   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23117                                    : InVec.getOperand(1);
23118   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23119                                  InVec.getOperand(0), Shuffle,
23120                                  &ShuffleMask[0]);
23121   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23122   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23123                      EltNo);
23124 }
23125
23126 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23127 /// special and don't usually play with other vector types, it's better to
23128 /// handle them early to be sure we emit efficient code by avoiding
23129 /// store-load conversions.
23130 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
23131   if (N->getValueType(0) != MVT::x86mmx ||
23132       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
23133       N->getOperand(0)->getValueType(0) != MVT::v2i32)
23134     return SDValue();
23135
23136   SDValue V = N->getOperand(0);
23137   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
23138   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
23139     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
23140                        N->getValueType(0), V.getOperand(0));
23141
23142   return SDValue();
23143 }
23144
23145 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23146 /// generation and convert it from being a bunch of shuffles and extracts
23147 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23148 /// storing the value and loading scalars back, while for x64 we should
23149 /// use 64-bit extracts and shifts.
23150 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23151                                          TargetLowering::DAGCombinerInfo &DCI) {
23152   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23153     return NewOp;
23154
23155   SDValue InputVector = N->getOperand(0);
23156   SDLoc dl(InputVector);
23157   // Detect mmx to i32 conversion through a v2i32 elt extract.
23158   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23159       N->getValueType(0) == MVT::i32 &&
23160       InputVector.getValueType() == MVT::v2i32) {
23161
23162     // The bitcast source is a direct mmx result.
23163     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23164     if (MMXSrc.getValueType() == MVT::x86mmx)
23165       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23166                          N->getValueType(0),
23167                          InputVector.getNode()->getOperand(0));
23168
23169     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23170     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23171         MMXSrc.getValueType() == MVT::i64) {
23172       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23173       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23174           MMXSrcOp.getValueType() == MVT::v1i64 &&
23175           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23176         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23177                            N->getValueType(0), MMXSrcOp.getOperand(0));
23178     }
23179   }
23180
23181   EVT VT = N->getValueType(0);
23182
23183   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
23184       InputVector.getOpcode() == ISD::BITCAST &&
23185       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
23186     uint64_t ExtractedElt =
23187         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23188     uint64_t InputValue =
23189         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23190     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23191     return DAG.getConstant(Res, dl, MVT::i1);
23192   }
23193   // Only operate on vectors of 4 elements, where the alternative shuffling
23194   // gets to be more expensive.
23195   if (InputVector.getValueType() != MVT::v4i32)
23196     return SDValue();
23197
23198   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23199   // single use which is a sign-extend or zero-extend, and all elements are
23200   // used.
23201   SmallVector<SDNode *, 4> Uses;
23202   unsigned ExtractedElements = 0;
23203   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23204        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23205     if (UI.getUse().getResNo() != InputVector.getResNo())
23206       return SDValue();
23207
23208     SDNode *Extract = *UI;
23209     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23210       return SDValue();
23211
23212     if (Extract->getValueType(0) != MVT::i32)
23213       return SDValue();
23214     if (!Extract->hasOneUse())
23215       return SDValue();
23216     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23217         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23218       return SDValue();
23219     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23220       return SDValue();
23221
23222     // Record which element was extracted.
23223     ExtractedElements |=
23224       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23225
23226     Uses.push_back(Extract);
23227   }
23228
23229   // If not all the elements were used, this may not be worthwhile.
23230   if (ExtractedElements != 15)
23231     return SDValue();
23232
23233   // Ok, we've now decided to do the transformation.
23234   // If 64-bit shifts are legal, use the extract-shift sequence,
23235   // otherwise bounce the vector off the cache.
23236   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23237   SDValue Vals[4];
23238
23239   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23240     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23241     auto &DL = DAG.getDataLayout();
23242     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23243     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23244       DAG.getConstant(0, dl, VecIdxTy));
23245     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23246       DAG.getConstant(1, dl, VecIdxTy));
23247
23248     SDValue ShAmt = DAG.getConstant(
23249         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23250     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23251     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23252       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23253     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23254     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23255       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23256   } else {
23257     // Store the value to a temporary stack slot.
23258     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23259     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23260       MachinePointerInfo(), false, false, 0);
23261
23262     EVT ElementType = InputVector.getValueType().getVectorElementType();
23263     unsigned EltSize = ElementType.getSizeInBits() / 8;
23264
23265     // Replace each use (extract) with a load of the appropriate element.
23266     for (unsigned i = 0; i < 4; ++i) {
23267       uint64_t Offset = EltSize * i;
23268       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23269       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23270
23271       SDValue ScalarAddr =
23272           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23273
23274       // Load the scalar.
23275       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23276                             ScalarAddr, MachinePointerInfo(),
23277                             false, false, false, 0);
23278
23279     }
23280   }
23281
23282   // Replace the extracts
23283   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23284     UE = Uses.end(); UI != UE; ++UI) {
23285     SDNode *Extract = *UI;
23286
23287     SDValue Idx = Extract->getOperand(1);
23288     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23289     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23290   }
23291
23292   // The replacement was made in place; don't return anything.
23293   return SDValue();
23294 }
23295
23296 static SDValue
23297 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23298                                       const X86Subtarget *Subtarget) {
23299   SDLoc dl(N);
23300   SDValue Cond = N->getOperand(0);
23301   SDValue LHS = N->getOperand(1);
23302   SDValue RHS = N->getOperand(2);
23303
23304   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23305     SDValue CondSrc = Cond->getOperand(0);
23306     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23307       Cond = CondSrc->getOperand(0);
23308   }
23309
23310   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23311     return SDValue();
23312
23313   // A vselect where all conditions and data are constants can be optimized into
23314   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23315   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23316       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23317     return SDValue();
23318
23319   unsigned MaskValue = 0;
23320   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23321     return SDValue();
23322
23323   MVT VT = N->getSimpleValueType(0);
23324   unsigned NumElems = VT.getVectorNumElements();
23325   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23326   for (unsigned i = 0; i < NumElems; ++i) {
23327     // Be sure we emit undef where we can.
23328     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23329       ShuffleMask[i] = -1;
23330     else
23331       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23332   }
23333
23334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23335   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23336     return SDValue();
23337   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23338 }
23339
23340 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23341 /// nodes.
23342 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23343                                     TargetLowering::DAGCombinerInfo &DCI,
23344                                     const X86Subtarget *Subtarget) {
23345   SDLoc DL(N);
23346   SDValue Cond = N->getOperand(0);
23347   // Get the LHS/RHS of the select.
23348   SDValue LHS = N->getOperand(1);
23349   SDValue RHS = N->getOperand(2);
23350   EVT VT = LHS.getValueType();
23351   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23352
23353   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23354   // instructions match the semantics of the common C idiom x<y?x:y but not
23355   // x<=y?x:y, because of how they handle negative zero (which can be
23356   // ignored in unsafe-math mode).
23357   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23358   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23359       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23360       (Subtarget->hasSSE2() ||
23361        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23362     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23363
23364     unsigned Opcode = 0;
23365     // Check for x CC y ? x : y.
23366     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23367         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23368       switch (CC) {
23369       default: break;
23370       case ISD::SETULT:
23371         // Converting this to a min would handle NaNs incorrectly, and swapping
23372         // the operands would cause it to handle comparisons between positive
23373         // and negative zero incorrectly.
23374         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23375           if (!DAG.getTarget().Options.UnsafeFPMath &&
23376               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23377             break;
23378           std::swap(LHS, RHS);
23379         }
23380         Opcode = X86ISD::FMIN;
23381         break;
23382       case ISD::SETOLE:
23383         // Converting this to a min would handle comparisons between positive
23384         // and negative zero incorrectly.
23385         if (!DAG.getTarget().Options.UnsafeFPMath &&
23386             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23387           break;
23388         Opcode = X86ISD::FMIN;
23389         break;
23390       case ISD::SETULE:
23391         // Converting this to a min would handle both negative zeros and NaNs
23392         // incorrectly, but we can swap the operands to fix both.
23393         std::swap(LHS, RHS);
23394       case ISD::SETOLT:
23395       case ISD::SETLT:
23396       case ISD::SETLE:
23397         Opcode = X86ISD::FMIN;
23398         break;
23399
23400       case ISD::SETOGE:
23401         // Converting this to a max would handle comparisons between positive
23402         // and negative zero incorrectly.
23403         if (!DAG.getTarget().Options.UnsafeFPMath &&
23404             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23405           break;
23406         Opcode = X86ISD::FMAX;
23407         break;
23408       case ISD::SETUGT:
23409         // Converting this to a max would handle NaNs incorrectly, and swapping
23410         // the operands would cause it to handle comparisons between positive
23411         // and negative zero incorrectly.
23412         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23413           if (!DAG.getTarget().Options.UnsafeFPMath &&
23414               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23415             break;
23416           std::swap(LHS, RHS);
23417         }
23418         Opcode = X86ISD::FMAX;
23419         break;
23420       case ISD::SETUGE:
23421         // Converting this to a max would handle both negative zeros and NaNs
23422         // incorrectly, but we can swap the operands to fix both.
23423         std::swap(LHS, RHS);
23424       case ISD::SETOGT:
23425       case ISD::SETGT:
23426       case ISD::SETGE:
23427         Opcode = X86ISD::FMAX;
23428         break;
23429       }
23430     // Check for x CC y ? y : x -- a min/max with reversed arms.
23431     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23432                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23433       switch (CC) {
23434       default: break;
23435       case ISD::SETOGE:
23436         // Converting this to a min would handle comparisons between positive
23437         // and negative zero incorrectly, and swapping the operands would
23438         // cause it to handle NaNs incorrectly.
23439         if (!DAG.getTarget().Options.UnsafeFPMath &&
23440             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23441           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23442             break;
23443           std::swap(LHS, RHS);
23444         }
23445         Opcode = X86ISD::FMIN;
23446         break;
23447       case ISD::SETUGT:
23448         // Converting this to a min would handle NaNs incorrectly.
23449         if (!DAG.getTarget().Options.UnsafeFPMath &&
23450             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23451           break;
23452         Opcode = X86ISD::FMIN;
23453         break;
23454       case ISD::SETUGE:
23455         // Converting this to a min would handle both negative zeros and NaNs
23456         // incorrectly, but we can swap the operands to fix both.
23457         std::swap(LHS, RHS);
23458       case ISD::SETOGT:
23459       case ISD::SETGT:
23460       case ISD::SETGE:
23461         Opcode = X86ISD::FMIN;
23462         break;
23463
23464       case ISD::SETULT:
23465         // Converting this to a max would handle NaNs incorrectly.
23466         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23467           break;
23468         Opcode = X86ISD::FMAX;
23469         break;
23470       case ISD::SETOLE:
23471         // Converting this to a max would handle comparisons between positive
23472         // and negative zero incorrectly, and swapping the operands would
23473         // cause it to handle NaNs incorrectly.
23474         if (!DAG.getTarget().Options.UnsafeFPMath &&
23475             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23476           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23477             break;
23478           std::swap(LHS, RHS);
23479         }
23480         Opcode = X86ISD::FMAX;
23481         break;
23482       case ISD::SETULE:
23483         // Converting this to a max would handle both negative zeros and NaNs
23484         // incorrectly, but we can swap the operands to fix both.
23485         std::swap(LHS, RHS);
23486       case ISD::SETOLT:
23487       case ISD::SETLT:
23488       case ISD::SETLE:
23489         Opcode = X86ISD::FMAX;
23490         break;
23491       }
23492     }
23493
23494     if (Opcode)
23495       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23496   }
23497
23498   EVT CondVT = Cond.getValueType();
23499   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23500       CondVT.getVectorElementType() == MVT::i1) {
23501     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23502     // lowering on KNL. In this case we convert it to
23503     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23504     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23505     // Since SKX these selects have a proper lowering.
23506     EVT OpVT = LHS.getValueType();
23507     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23508         (OpVT.getVectorElementType() == MVT::i8 ||
23509          OpVT.getVectorElementType() == MVT::i16) &&
23510         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23511       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23512       DCI.AddToWorklist(Cond.getNode());
23513       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23514     }
23515   }
23516   // If this is a select between two integer constants, try to do some
23517   // optimizations.
23518   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23519     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23520       // Don't do this for crazy integer types.
23521       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23522         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23523         // so that TrueC (the true value) is larger than FalseC.
23524         bool NeedsCondInvert = false;
23525
23526         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23527             // Efficiently invertible.
23528             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23529              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23530               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23531           NeedsCondInvert = true;
23532           std::swap(TrueC, FalseC);
23533         }
23534
23535         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23536         if (FalseC->getAPIntValue() == 0 &&
23537             TrueC->getAPIntValue().isPowerOf2()) {
23538           if (NeedsCondInvert) // Invert the condition if needed.
23539             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23540                                DAG.getConstant(1, DL, Cond.getValueType()));
23541
23542           // Zero extend the condition if needed.
23543           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23544
23545           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23546           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23547                              DAG.getConstant(ShAmt, DL, MVT::i8));
23548         }
23549
23550         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23551         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23552           if (NeedsCondInvert) // Invert the condition if needed.
23553             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23554                                DAG.getConstant(1, DL, Cond.getValueType()));
23555
23556           // Zero extend the condition if needed.
23557           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23558                              FalseC->getValueType(0), Cond);
23559           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23560                              SDValue(FalseC, 0));
23561         }
23562
23563         // Optimize cases that will turn into an LEA instruction.  This requires
23564         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23565         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23566           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23567           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23568
23569           bool isFastMultiplier = false;
23570           if (Diff < 10) {
23571             switch ((unsigned char)Diff) {
23572               default: break;
23573               case 1:  // result = add base, cond
23574               case 2:  // result = lea base(    , cond*2)
23575               case 3:  // result = lea base(cond, cond*2)
23576               case 4:  // result = lea base(    , cond*4)
23577               case 5:  // result = lea base(cond, cond*4)
23578               case 8:  // result = lea base(    , cond*8)
23579               case 9:  // result = lea base(cond, cond*8)
23580                 isFastMultiplier = true;
23581                 break;
23582             }
23583           }
23584
23585           if (isFastMultiplier) {
23586             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23587             if (NeedsCondInvert) // Invert the condition if needed.
23588               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23589                                  DAG.getConstant(1, DL, Cond.getValueType()));
23590
23591             // Zero extend the condition if needed.
23592             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23593                                Cond);
23594             // Scale the condition by the difference.
23595             if (Diff != 1)
23596               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23597                                  DAG.getConstant(Diff, DL,
23598                                                  Cond.getValueType()));
23599
23600             // Add the base if non-zero.
23601             if (FalseC->getAPIntValue() != 0)
23602               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23603                                  SDValue(FalseC, 0));
23604             return Cond;
23605           }
23606         }
23607       }
23608   }
23609
23610   // Canonicalize max and min:
23611   // (x > y) ? x : y -> (x >= y) ? x : y
23612   // (x < y) ? x : y -> (x <= y) ? x : y
23613   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23614   // the need for an extra compare
23615   // against zero. e.g.
23616   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23617   // subl   %esi, %edi
23618   // testl  %edi, %edi
23619   // movl   $0, %eax
23620   // cmovgl %edi, %eax
23621   // =>
23622   // xorl   %eax, %eax
23623   // subl   %esi, $edi
23624   // cmovsl %eax, %edi
23625   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23626       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23627       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23628     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23629     switch (CC) {
23630     default: break;
23631     case ISD::SETLT:
23632     case ISD::SETGT: {
23633       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23634       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23635                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23636       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23637     }
23638     }
23639   }
23640
23641   // Early exit check
23642   if (!TLI.isTypeLegal(VT))
23643     return SDValue();
23644
23645   // Match VSELECTs into subs with unsigned saturation.
23646   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23647       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23648       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23649        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23650     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23651
23652     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23653     // left side invert the predicate to simplify logic below.
23654     SDValue Other;
23655     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23656       Other = RHS;
23657       CC = ISD::getSetCCInverse(CC, true);
23658     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23659       Other = LHS;
23660     }
23661
23662     if (Other.getNode() && Other->getNumOperands() == 2 &&
23663         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23664       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23665       SDValue CondRHS = Cond->getOperand(1);
23666
23667       // Look for a general sub with unsigned saturation first.
23668       // x >= y ? x-y : 0 --> subus x, y
23669       // x >  y ? x-y : 0 --> subus x, y
23670       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23671           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23672         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23673
23674       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23675         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23676           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23677             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23678               // If the RHS is a constant we have to reverse the const
23679               // canonicalization.
23680               // x > C-1 ? x+-C : 0 --> subus x, C
23681               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23682                   CondRHSConst->getAPIntValue() ==
23683                       (-OpRHSConst->getAPIntValue() - 1))
23684                 return DAG.getNode(
23685                     X86ISD::SUBUS, DL, VT, OpLHS,
23686                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23687
23688           // Another special case: If C was a sign bit, the sub has been
23689           // canonicalized into a xor.
23690           // FIXME: Would it be better to use computeKnownBits to determine
23691           //        whether it's safe to decanonicalize the xor?
23692           // x s< 0 ? x^C : 0 --> subus x, C
23693           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23694               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23695               OpRHSConst->getAPIntValue().isSignBit())
23696             // Note that we have to rebuild the RHS constant here to ensure we
23697             // don't rely on particular values of undef lanes.
23698             return DAG.getNode(
23699                 X86ISD::SUBUS, DL, VT, OpLHS,
23700                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23701         }
23702     }
23703   }
23704
23705   // Simplify vector selection if condition value type matches vselect
23706   // operand type
23707   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23708     assert(Cond.getValueType().isVector() &&
23709            "vector select expects a vector selector!");
23710
23711     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23712     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23713
23714     // Try invert the condition if true value is not all 1s and false value
23715     // is not all 0s.
23716     if (!TValIsAllOnes && !FValIsAllZeros &&
23717         // Check if the selector will be produced by CMPP*/PCMP*
23718         Cond.getOpcode() == ISD::SETCC &&
23719         // Check if SETCC has already been promoted
23720         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23721             CondVT) {
23722       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23723       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23724
23725       if (TValIsAllZeros || FValIsAllOnes) {
23726         SDValue CC = Cond.getOperand(2);
23727         ISD::CondCode NewCC =
23728           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23729                                Cond.getOperand(0).getValueType().isInteger());
23730         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23731         std::swap(LHS, RHS);
23732         TValIsAllOnes = FValIsAllOnes;
23733         FValIsAllZeros = TValIsAllZeros;
23734       }
23735     }
23736
23737     if (TValIsAllOnes || FValIsAllZeros) {
23738       SDValue Ret;
23739
23740       if (TValIsAllOnes && FValIsAllZeros)
23741         Ret = Cond;
23742       else if (TValIsAllOnes)
23743         Ret =
23744             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23745       else if (FValIsAllZeros)
23746         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23747                           DAG.getBitcast(CondVT, LHS));
23748
23749       return DAG.getBitcast(VT, Ret);
23750     }
23751   }
23752
23753   // We should generate an X86ISD::BLENDI from a vselect if its argument
23754   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23755   // constants. This specific pattern gets generated when we split a
23756   // selector for a 512 bit vector in a machine without AVX512 (but with
23757   // 256-bit vectors), during legalization:
23758   //
23759   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23760   //
23761   // Iff we find this pattern and the build_vectors are built from
23762   // constants, we translate the vselect into a shuffle_vector that we
23763   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23764   if ((N->getOpcode() == ISD::VSELECT ||
23765        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23766       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23767     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23768     if (Shuffle.getNode())
23769       return Shuffle;
23770   }
23771
23772   // If this is a *dynamic* select (non-constant condition) and we can match
23773   // this node with one of the variable blend instructions, restructure the
23774   // condition so that the blends can use the high bit of each element and use
23775   // SimplifyDemandedBits to simplify the condition operand.
23776   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23777       !DCI.isBeforeLegalize() &&
23778       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23779     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23780
23781     // Don't optimize vector selects that map to mask-registers.
23782     if (BitWidth == 1)
23783       return SDValue();
23784
23785     // We can only handle the cases where VSELECT is directly legal on the
23786     // subtarget. We custom lower VSELECT nodes with constant conditions and
23787     // this makes it hard to see whether a dynamic VSELECT will correctly
23788     // lower, so we both check the operation's status and explicitly handle the
23789     // cases where a *dynamic* blend will fail even though a constant-condition
23790     // blend could be custom lowered.
23791     // FIXME: We should find a better way to handle this class of problems.
23792     // Potentially, we should combine constant-condition vselect nodes
23793     // pre-legalization into shuffles and not mark as many types as custom
23794     // lowered.
23795     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23796       return SDValue();
23797     // FIXME: We don't support i16-element blends currently. We could and
23798     // should support them by making *all* the bits in the condition be set
23799     // rather than just the high bit and using an i8-element blend.
23800     if (VT.getScalarType() == MVT::i16)
23801       return SDValue();
23802     // Dynamic blending was only available from SSE4.1 onward.
23803     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23804       return SDValue();
23805     // Byte blends are only available in AVX2
23806     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23807         !Subtarget->hasAVX2())
23808       return SDValue();
23809
23810     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23811     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23812
23813     APInt KnownZero, KnownOne;
23814     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23815                                           DCI.isBeforeLegalizeOps());
23816     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23817         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23818                                  TLO)) {
23819       // If we changed the computation somewhere in the DAG, this change
23820       // will affect all users of Cond.
23821       // Make sure it is fine and update all the nodes so that we do not
23822       // use the generic VSELECT anymore. Otherwise, we may perform
23823       // wrong optimizations as we messed up with the actual expectation
23824       // for the vector boolean values.
23825       if (Cond != TLO.Old) {
23826         // Check all uses of that condition operand to check whether it will be
23827         // consumed by non-BLEND instructions, which may depend on all bits are
23828         // set properly.
23829         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23830              I != E; ++I)
23831           if (I->getOpcode() != ISD::VSELECT)
23832             // TODO: Add other opcodes eventually lowered into BLEND.
23833             return SDValue();
23834
23835         // Update all the users of the condition, before committing the change,
23836         // so that the VSELECT optimizations that expect the correct vector
23837         // boolean value will not be triggered.
23838         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23839              I != E; ++I)
23840           DAG.ReplaceAllUsesOfValueWith(
23841               SDValue(*I, 0),
23842               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23843                           Cond, I->getOperand(1), I->getOperand(2)));
23844         DCI.CommitTargetLoweringOpt(TLO);
23845         return SDValue();
23846       }
23847       // At this point, only Cond is changed. Change the condition
23848       // just for N to keep the opportunity to optimize all other
23849       // users their own way.
23850       DAG.ReplaceAllUsesOfValueWith(
23851           SDValue(N, 0),
23852           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23853                       TLO.New, N->getOperand(1), N->getOperand(2)));
23854       return SDValue();
23855     }
23856   }
23857
23858   return SDValue();
23859 }
23860
23861 // Check whether a boolean test is testing a boolean value generated by
23862 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23863 // code.
23864 //
23865 // Simplify the following patterns:
23866 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23867 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23868 // to (Op EFLAGS Cond)
23869 //
23870 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23871 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23872 // to (Op EFLAGS !Cond)
23873 //
23874 // where Op could be BRCOND or CMOV.
23875 //
23876 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23877   // Quit if not CMP and SUB with its value result used.
23878   if (Cmp.getOpcode() != X86ISD::CMP &&
23879       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23880       return SDValue();
23881
23882   // Quit if not used as a boolean value.
23883   if (CC != X86::COND_E && CC != X86::COND_NE)
23884     return SDValue();
23885
23886   // Check CMP operands. One of them should be 0 or 1 and the other should be
23887   // an SetCC or extended from it.
23888   SDValue Op1 = Cmp.getOperand(0);
23889   SDValue Op2 = Cmp.getOperand(1);
23890
23891   SDValue SetCC;
23892   const ConstantSDNode* C = nullptr;
23893   bool needOppositeCond = (CC == X86::COND_E);
23894   bool checkAgainstTrue = false; // Is it a comparison against 1?
23895
23896   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23897     SetCC = Op2;
23898   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23899     SetCC = Op1;
23900   else // Quit if all operands are not constants.
23901     return SDValue();
23902
23903   if (C->getZExtValue() == 1) {
23904     needOppositeCond = !needOppositeCond;
23905     checkAgainstTrue = true;
23906   } else if (C->getZExtValue() != 0)
23907     // Quit if the constant is neither 0 or 1.
23908     return SDValue();
23909
23910   bool truncatedToBoolWithAnd = false;
23911   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23912   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23913          SetCC.getOpcode() == ISD::TRUNCATE ||
23914          SetCC.getOpcode() == ISD::AND) {
23915     if (SetCC.getOpcode() == ISD::AND) {
23916       int OpIdx = -1;
23917       ConstantSDNode *CS;
23918       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23919           CS->getZExtValue() == 1)
23920         OpIdx = 1;
23921       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23922           CS->getZExtValue() == 1)
23923         OpIdx = 0;
23924       if (OpIdx == -1)
23925         break;
23926       SetCC = SetCC.getOperand(OpIdx);
23927       truncatedToBoolWithAnd = true;
23928     } else
23929       SetCC = SetCC.getOperand(0);
23930   }
23931
23932   switch (SetCC.getOpcode()) {
23933   case X86ISD::SETCC_CARRY:
23934     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23935     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23936     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23937     // truncated to i1 using 'and'.
23938     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23939       break;
23940     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23941            "Invalid use of SETCC_CARRY!");
23942     // FALL THROUGH
23943   case X86ISD::SETCC:
23944     // Set the condition code or opposite one if necessary.
23945     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23946     if (needOppositeCond)
23947       CC = X86::GetOppositeBranchCondition(CC);
23948     return SetCC.getOperand(1);
23949   case X86ISD::CMOV: {
23950     // Check whether false/true value has canonical one, i.e. 0 or 1.
23951     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23952     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23953     // Quit if true value is not a constant.
23954     if (!TVal)
23955       return SDValue();
23956     // Quit if false value is not a constant.
23957     if (!FVal) {
23958       SDValue Op = SetCC.getOperand(0);
23959       // Skip 'zext' or 'trunc' node.
23960       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23961           Op.getOpcode() == ISD::TRUNCATE)
23962         Op = Op.getOperand(0);
23963       // A special case for rdrand/rdseed, where 0 is set if false cond is
23964       // found.
23965       if ((Op.getOpcode() != X86ISD::RDRAND &&
23966            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23967         return SDValue();
23968     }
23969     // Quit if false value is not the constant 0 or 1.
23970     bool FValIsFalse = true;
23971     if (FVal && FVal->getZExtValue() != 0) {
23972       if (FVal->getZExtValue() != 1)
23973         return SDValue();
23974       // If FVal is 1, opposite cond is needed.
23975       needOppositeCond = !needOppositeCond;
23976       FValIsFalse = false;
23977     }
23978     // Quit if TVal is not the constant opposite of FVal.
23979     if (FValIsFalse && TVal->getZExtValue() != 1)
23980       return SDValue();
23981     if (!FValIsFalse && TVal->getZExtValue() != 0)
23982       return SDValue();
23983     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23984     if (needOppositeCond)
23985       CC = X86::GetOppositeBranchCondition(CC);
23986     return SetCC.getOperand(3);
23987   }
23988   }
23989
23990   return SDValue();
23991 }
23992
23993 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23994 /// Match:
23995 ///   (X86or (X86setcc) (X86setcc))
23996 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23997 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23998                                            X86::CondCode &CC1, SDValue &Flags,
23999                                            bool &isAnd) {
24000   if (Cond->getOpcode() == X86ISD::CMP) {
24001     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
24002     if (!CondOp1C || !CondOp1C->isNullValue())
24003       return false;
24004
24005     Cond = Cond->getOperand(0);
24006   }
24007
24008   isAnd = false;
24009
24010   SDValue SetCC0, SetCC1;
24011   switch (Cond->getOpcode()) {
24012   default: return false;
24013   case ISD::AND:
24014   case X86ISD::AND:
24015     isAnd = true;
24016     // fallthru
24017   case ISD::OR:
24018   case X86ISD::OR:
24019     SetCC0 = Cond->getOperand(0);
24020     SetCC1 = Cond->getOperand(1);
24021     break;
24022   };
24023
24024   // Make sure we have SETCC nodes, using the same flags value.
24025   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24026       SetCC1.getOpcode() != X86ISD::SETCC ||
24027       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24028     return false;
24029
24030   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24031   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24032   Flags = SetCC0->getOperand(1);
24033   return true;
24034 }
24035
24036 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24037 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24038                                   TargetLowering::DAGCombinerInfo &DCI,
24039                                   const X86Subtarget *Subtarget) {
24040   SDLoc DL(N);
24041
24042   // If the flag operand isn't dead, don't touch this CMOV.
24043   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24044     return SDValue();
24045
24046   SDValue FalseOp = N->getOperand(0);
24047   SDValue TrueOp = N->getOperand(1);
24048   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24049   SDValue Cond = N->getOperand(3);
24050
24051   if (CC == X86::COND_E || CC == X86::COND_NE) {
24052     switch (Cond.getOpcode()) {
24053     default: break;
24054     case X86ISD::BSR:
24055     case X86ISD::BSF:
24056       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24057       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24058         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24059     }
24060   }
24061
24062   SDValue Flags;
24063
24064   Flags = checkBoolTestSetCCCombine(Cond, CC);
24065   if (Flags.getNode() &&
24066       // Extra check as FCMOV only supports a subset of X86 cond.
24067       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24068     SDValue Ops[] = { FalseOp, TrueOp,
24069                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24070     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24071   }
24072
24073   // If this is a select between two integer constants, try to do some
24074   // optimizations.  Note that the operands are ordered the opposite of SELECT
24075   // operands.
24076   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24077     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24078       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24079       // larger than FalseC (the false value).
24080       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24081         CC = X86::GetOppositeBranchCondition(CC);
24082         std::swap(TrueC, FalseC);
24083         std::swap(TrueOp, FalseOp);
24084       }
24085
24086       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24087       // This is efficient for any integer data type (including i8/i16) and
24088       // shift amount.
24089       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24090         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24091                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24092
24093         // Zero extend the condition if needed.
24094         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24095
24096         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24097         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24098                            DAG.getConstant(ShAmt, DL, MVT::i8));
24099         if (N->getNumValues() == 2)  // Dead flag value?
24100           return DCI.CombineTo(N, Cond, SDValue());
24101         return Cond;
24102       }
24103
24104       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24105       // for any integer data type, including i8/i16.
24106       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24107         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24108                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24109
24110         // Zero extend the condition if needed.
24111         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24112                            FalseC->getValueType(0), Cond);
24113         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24114                            SDValue(FalseC, 0));
24115
24116         if (N->getNumValues() == 2)  // Dead flag value?
24117           return DCI.CombineTo(N, Cond, SDValue());
24118         return Cond;
24119       }
24120
24121       // Optimize cases that will turn into an LEA instruction.  This requires
24122       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24123       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24124         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24125         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24126
24127         bool isFastMultiplier = false;
24128         if (Diff < 10) {
24129           switch ((unsigned char)Diff) {
24130           default: break;
24131           case 1:  // result = add base, cond
24132           case 2:  // result = lea base(    , cond*2)
24133           case 3:  // result = lea base(cond, cond*2)
24134           case 4:  // result = lea base(    , cond*4)
24135           case 5:  // result = lea base(cond, cond*4)
24136           case 8:  // result = lea base(    , cond*8)
24137           case 9:  // result = lea base(cond, cond*8)
24138             isFastMultiplier = true;
24139             break;
24140           }
24141         }
24142
24143         if (isFastMultiplier) {
24144           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24145           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24146                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24147           // Zero extend the condition if needed.
24148           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24149                              Cond);
24150           // Scale the condition by the difference.
24151           if (Diff != 1)
24152             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24153                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24154
24155           // Add the base if non-zero.
24156           if (FalseC->getAPIntValue() != 0)
24157             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24158                                SDValue(FalseC, 0));
24159           if (N->getNumValues() == 2)  // Dead flag value?
24160             return DCI.CombineTo(N, Cond, SDValue());
24161           return Cond;
24162         }
24163       }
24164     }
24165   }
24166
24167   // Handle these cases:
24168   //   (select (x != c), e, c) -> select (x != c), e, x),
24169   //   (select (x == c), c, e) -> select (x == c), x, e)
24170   // where the c is an integer constant, and the "select" is the combination
24171   // of CMOV and CMP.
24172   //
24173   // The rationale for this change is that the conditional-move from a constant
24174   // needs two instructions, however, conditional-move from a register needs
24175   // only one instruction.
24176   //
24177   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24178   //  some instruction-combining opportunities. This opt needs to be
24179   //  postponed as late as possible.
24180   //
24181   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24182     // the DCI.xxxx conditions are provided to postpone the optimization as
24183     // late as possible.
24184
24185     ConstantSDNode *CmpAgainst = nullptr;
24186     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24187         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24188         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24189
24190       if (CC == X86::COND_NE &&
24191           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24192         CC = X86::GetOppositeBranchCondition(CC);
24193         std::swap(TrueOp, FalseOp);
24194       }
24195
24196       if (CC == X86::COND_E &&
24197           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24198         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24199                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24200         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24201       }
24202     }
24203   }
24204
24205   // Fold and/or of setcc's to double CMOV:
24206   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24207   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24208   //
24209   // This combine lets us generate:
24210   //   cmovcc1 (jcc1 if we don't have CMOV)
24211   //   cmovcc2 (same)
24212   // instead of:
24213   //   setcc1
24214   //   setcc2
24215   //   and/or
24216   //   cmovne (jne if we don't have CMOV)
24217   // When we can't use the CMOV instruction, it might increase branch
24218   // mispredicts.
24219   // When we can use CMOV, or when there is no mispredict, this improves
24220   // throughput and reduces register pressure.
24221   //
24222   if (CC == X86::COND_NE) {
24223     SDValue Flags;
24224     X86::CondCode CC0, CC1;
24225     bool isAndSetCC;
24226     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24227       if (isAndSetCC) {
24228         std::swap(FalseOp, TrueOp);
24229         CC0 = X86::GetOppositeBranchCondition(CC0);
24230         CC1 = X86::GetOppositeBranchCondition(CC1);
24231       }
24232
24233       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24234         Flags};
24235       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24236       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24237       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24238       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24239       return CMOV;
24240     }
24241   }
24242
24243   return SDValue();
24244 }
24245
24246 /// PerformMulCombine - Optimize a single multiply with constant into two
24247 /// in order to implement it with two cheaper instructions, e.g.
24248 /// LEA + SHL, LEA + LEA.
24249 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24250                                  TargetLowering::DAGCombinerInfo &DCI) {
24251   // An imul is usually smaller than the alternative sequence.
24252   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24253     return SDValue();
24254
24255   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24256     return SDValue();
24257
24258   EVT VT = N->getValueType(0);
24259   if (VT != MVT::i64 && VT != MVT::i32)
24260     return SDValue();
24261
24262   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24263   if (!C)
24264     return SDValue();
24265   uint64_t MulAmt = C->getZExtValue();
24266   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24267     return SDValue();
24268
24269   uint64_t MulAmt1 = 0;
24270   uint64_t MulAmt2 = 0;
24271   if ((MulAmt % 9) == 0) {
24272     MulAmt1 = 9;
24273     MulAmt2 = MulAmt / 9;
24274   } else if ((MulAmt % 5) == 0) {
24275     MulAmt1 = 5;
24276     MulAmt2 = MulAmt / 5;
24277   } else if ((MulAmt % 3) == 0) {
24278     MulAmt1 = 3;
24279     MulAmt2 = MulAmt / 3;
24280   }
24281   if (MulAmt2 &&
24282       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24283     SDLoc DL(N);
24284
24285     if (isPowerOf2_64(MulAmt2) &&
24286         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24287       // If second multiplifer is pow2, issue it first. We want the multiply by
24288       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24289       // is an add.
24290       std::swap(MulAmt1, MulAmt2);
24291
24292     SDValue NewMul;
24293     if (isPowerOf2_64(MulAmt1))
24294       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24295                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24296     else
24297       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24298                            DAG.getConstant(MulAmt1, DL, VT));
24299
24300     if (isPowerOf2_64(MulAmt2))
24301       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24302                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24303     else
24304       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24305                            DAG.getConstant(MulAmt2, DL, VT));
24306
24307     // Do not add new nodes to DAG combiner worklist.
24308     DCI.CombineTo(N, NewMul, false);
24309   }
24310   return SDValue();
24311 }
24312
24313 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24314   SDValue N0 = N->getOperand(0);
24315   SDValue N1 = N->getOperand(1);
24316   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24317   EVT VT = N0.getValueType();
24318
24319   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24320   // since the result of setcc_c is all zero's or all ones.
24321   if (VT.isInteger() && !VT.isVector() &&
24322       N1C && N0.getOpcode() == ISD::AND &&
24323       N0.getOperand(1).getOpcode() == ISD::Constant) {
24324     SDValue N00 = N0.getOperand(0);
24325     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24326     APInt ShAmt = N1C->getAPIntValue();
24327     Mask = Mask.shl(ShAmt);
24328     bool MaskOK = false;
24329     // We can handle cases concerning bit-widening nodes containing setcc_c if
24330     // we carefully interrogate the mask to make sure we are semantics
24331     // preserving.
24332     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24333     // of the underlying setcc_c operation if the setcc_c was zero extended.
24334     // Consider the following example:
24335     //   zext(setcc_c)                 -> i32 0x0000FFFF
24336     //   c1                            -> i32 0x0000FFFF
24337     //   c2                            -> i32 0x00000001
24338     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24339     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24340     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24341       MaskOK = true;
24342     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24343                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24344       MaskOK = true;
24345     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24346                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24347                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24348       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24349     }
24350     if (MaskOK && Mask != 0) {
24351       SDLoc DL(N);
24352       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24353     }
24354   }
24355
24356   // Hardware support for vector shifts is sparse which makes us scalarize the
24357   // vector operations in many cases. Also, on sandybridge ADD is faster than
24358   // shl.
24359   // (shl V, 1) -> add V,V
24360   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24361     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24362       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24363       // We shift all of the values by one. In many cases we do not have
24364       // hardware support for this operation. This is better expressed as an ADD
24365       // of two values.
24366       if (N1SplatC->getAPIntValue() == 1)
24367         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24368     }
24369
24370   return SDValue();
24371 }
24372
24373 /// \brief Returns a vector of 0s if the node in input is a vector logical
24374 /// shift by a constant amount which is known to be bigger than or equal
24375 /// to the vector element size in bits.
24376 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24377                                       const X86Subtarget *Subtarget) {
24378   EVT VT = N->getValueType(0);
24379
24380   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24381       (!Subtarget->hasInt256() ||
24382        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24383     return SDValue();
24384
24385   SDValue Amt = N->getOperand(1);
24386   SDLoc DL(N);
24387   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24388     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24389       APInt ShiftAmt = AmtSplat->getAPIntValue();
24390       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24391
24392       // SSE2/AVX2 logical shifts always return a vector of 0s
24393       // if the shift amount is bigger than or equal to
24394       // the element size. The constant shift amount will be
24395       // encoded as a 8-bit immediate.
24396       if (ShiftAmt.trunc(8).uge(MaxAmount))
24397         return getZeroVector(VT, Subtarget, DAG, DL);
24398     }
24399
24400   return SDValue();
24401 }
24402
24403 /// PerformShiftCombine - Combine shifts.
24404 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24405                                    TargetLowering::DAGCombinerInfo &DCI,
24406                                    const X86Subtarget *Subtarget) {
24407   if (N->getOpcode() == ISD::SHL)
24408     if (SDValue V = PerformSHLCombine(N, DAG))
24409       return V;
24410
24411   // Try to fold this logical shift into a zero vector.
24412   if (N->getOpcode() != ISD::SRA)
24413     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24414       return V;
24415
24416   return SDValue();
24417 }
24418
24419 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24420 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24421 // and friends.  Likewise for OR -> CMPNEQSS.
24422 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24423                             TargetLowering::DAGCombinerInfo &DCI,
24424                             const X86Subtarget *Subtarget) {
24425   unsigned opcode;
24426
24427   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24428   // we're requiring SSE2 for both.
24429   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24430     SDValue N0 = N->getOperand(0);
24431     SDValue N1 = N->getOperand(1);
24432     SDValue CMP0 = N0->getOperand(1);
24433     SDValue CMP1 = N1->getOperand(1);
24434     SDLoc DL(N);
24435
24436     // The SETCCs should both refer to the same CMP.
24437     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24438       return SDValue();
24439
24440     SDValue CMP00 = CMP0->getOperand(0);
24441     SDValue CMP01 = CMP0->getOperand(1);
24442     EVT     VT    = CMP00.getValueType();
24443
24444     if (VT == MVT::f32 || VT == MVT::f64) {
24445       bool ExpectingFlags = false;
24446       // Check for any users that want flags:
24447       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24448            !ExpectingFlags && UI != UE; ++UI)
24449         switch (UI->getOpcode()) {
24450         default:
24451         case ISD::BR_CC:
24452         case ISD::BRCOND:
24453         case ISD::SELECT:
24454           ExpectingFlags = true;
24455           break;
24456         case ISD::CopyToReg:
24457         case ISD::SIGN_EXTEND:
24458         case ISD::ZERO_EXTEND:
24459         case ISD::ANY_EXTEND:
24460           break;
24461         }
24462
24463       if (!ExpectingFlags) {
24464         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24465         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24466
24467         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24468           X86::CondCode tmp = cc0;
24469           cc0 = cc1;
24470           cc1 = tmp;
24471         }
24472
24473         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24474             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24475           // FIXME: need symbolic constants for these magic numbers.
24476           // See X86ATTInstPrinter.cpp:printSSECC().
24477           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24478           if (Subtarget->hasAVX512()) {
24479             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24480                                          CMP01,
24481                                          DAG.getConstant(x86cc, DL, MVT::i8));
24482             if (N->getValueType(0) != MVT::i1)
24483               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24484                                  FSetCC);
24485             return FSetCC;
24486           }
24487           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24488                                               CMP00.getValueType(), CMP00, CMP01,
24489                                               DAG.getConstant(x86cc, DL,
24490                                                               MVT::i8));
24491
24492           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24493           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24494
24495           if (is64BitFP && !Subtarget->is64Bit()) {
24496             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24497             // 64-bit integer, since that's not a legal type. Since
24498             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24499             // bits, but can do this little dance to extract the lowest 32 bits
24500             // and work with those going forward.
24501             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24502                                            OnesOrZeroesF);
24503             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24504             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24505                                         Vector32, DAG.getIntPtrConstant(0, DL));
24506             IntVT = MVT::i32;
24507           }
24508
24509           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24510           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24511                                       DAG.getConstant(1, DL, IntVT));
24512           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24513                                               ANDed);
24514           return OneBitOfTruth;
24515         }
24516       }
24517     }
24518   }
24519   return SDValue();
24520 }
24521
24522 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24523 /// so it can be folded inside ANDNP.
24524 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24525   EVT VT = N->getValueType(0);
24526
24527   // Match direct AllOnes for 128 and 256-bit vectors
24528   if (ISD::isBuildVectorAllOnes(N))
24529     return true;
24530
24531   // Look through a bit convert.
24532   if (N->getOpcode() == ISD::BITCAST)
24533     N = N->getOperand(0).getNode();
24534
24535   // Sometimes the operand may come from a insert_subvector building a 256-bit
24536   // allones vector
24537   if (VT.is256BitVector() &&
24538       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24539     SDValue V1 = N->getOperand(0);
24540     SDValue V2 = N->getOperand(1);
24541
24542     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24543         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24544         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24545         ISD::isBuildVectorAllOnes(V2.getNode()))
24546       return true;
24547   }
24548
24549   return false;
24550 }
24551
24552 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24553 // register. In most cases we actually compare or select YMM-sized registers
24554 // and mixing the two types creates horrible code. This method optimizes
24555 // some of the transition sequences.
24556 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24557                                  TargetLowering::DAGCombinerInfo &DCI,
24558                                  const X86Subtarget *Subtarget) {
24559   EVT VT = N->getValueType(0);
24560   if (!VT.is256BitVector())
24561     return SDValue();
24562
24563   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24564           N->getOpcode() == ISD::ZERO_EXTEND ||
24565           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24566
24567   SDValue Narrow = N->getOperand(0);
24568   EVT NarrowVT = Narrow->getValueType(0);
24569   if (!NarrowVT.is128BitVector())
24570     return SDValue();
24571
24572   if (Narrow->getOpcode() != ISD::XOR &&
24573       Narrow->getOpcode() != ISD::AND &&
24574       Narrow->getOpcode() != ISD::OR)
24575     return SDValue();
24576
24577   SDValue N0  = Narrow->getOperand(0);
24578   SDValue N1  = Narrow->getOperand(1);
24579   SDLoc DL(Narrow);
24580
24581   // The Left side has to be a trunc.
24582   if (N0.getOpcode() != ISD::TRUNCATE)
24583     return SDValue();
24584
24585   // The type of the truncated inputs.
24586   EVT WideVT = N0->getOperand(0)->getValueType(0);
24587   if (WideVT != VT)
24588     return SDValue();
24589
24590   // The right side has to be a 'trunc' or a constant vector.
24591   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24592   ConstantSDNode *RHSConstSplat = nullptr;
24593   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24594     RHSConstSplat = RHSBV->getConstantSplatNode();
24595   if (!RHSTrunc && !RHSConstSplat)
24596     return SDValue();
24597
24598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24599
24600   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24601     return SDValue();
24602
24603   // Set N0 and N1 to hold the inputs to the new wide operation.
24604   N0 = N0->getOperand(0);
24605   if (RHSConstSplat) {
24606     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24607                      SDValue(RHSConstSplat, 0));
24608     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24609     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24610   } else if (RHSTrunc) {
24611     N1 = N1->getOperand(0);
24612   }
24613
24614   // Generate the wide operation.
24615   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24616   unsigned Opcode = N->getOpcode();
24617   switch (Opcode) {
24618   case ISD::ANY_EXTEND:
24619     return Op;
24620   case ISD::ZERO_EXTEND: {
24621     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24622     APInt Mask = APInt::getAllOnesValue(InBits);
24623     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24624     return DAG.getNode(ISD::AND, DL, VT,
24625                        Op, DAG.getConstant(Mask, DL, VT));
24626   }
24627   case ISD::SIGN_EXTEND:
24628     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24629                        Op, DAG.getValueType(NarrowVT));
24630   default:
24631     llvm_unreachable("Unexpected opcode");
24632   }
24633 }
24634
24635 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24636                                  TargetLowering::DAGCombinerInfo &DCI,
24637                                  const X86Subtarget *Subtarget) {
24638   SDValue N0 = N->getOperand(0);
24639   SDValue N1 = N->getOperand(1);
24640   SDLoc DL(N);
24641
24642   // A vector zext_in_reg may be represented as a shuffle,
24643   // feeding into a bitcast (this represents anyext) feeding into
24644   // an and with a mask.
24645   // We'd like to try to combine that into a shuffle with zero
24646   // plus a bitcast, removing the and.
24647   if (N0.getOpcode() != ISD::BITCAST ||
24648       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24649     return SDValue();
24650
24651   // The other side of the AND should be a splat of 2^C, where C
24652   // is the number of bits in the source type.
24653   if (N1.getOpcode() == ISD::BITCAST)
24654     N1 = N1.getOperand(0);
24655   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24656     return SDValue();
24657   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24658
24659   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24660   EVT SrcType = Shuffle->getValueType(0);
24661
24662   // We expect a single-source shuffle
24663   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24664     return SDValue();
24665
24666   unsigned SrcSize = SrcType.getScalarSizeInBits();
24667
24668   APInt SplatValue, SplatUndef;
24669   unsigned SplatBitSize;
24670   bool HasAnyUndefs;
24671   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24672                                 SplatBitSize, HasAnyUndefs))
24673     return SDValue();
24674
24675   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24676   // Make sure the splat matches the mask we expect
24677   if (SplatBitSize > ResSize ||
24678       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24679     return SDValue();
24680
24681   // Make sure the input and output size make sense
24682   if (SrcSize >= ResSize || ResSize % SrcSize)
24683     return SDValue();
24684
24685   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24686   // The number of u's between each two values depends on the ratio between
24687   // the source and dest type.
24688   unsigned ZextRatio = ResSize / SrcSize;
24689   bool IsZext = true;
24690   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24691     if (i % ZextRatio) {
24692       if (Shuffle->getMaskElt(i) > 0) {
24693         // Expected undef
24694         IsZext = false;
24695         break;
24696       }
24697     } else {
24698       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24699         // Expected element number
24700         IsZext = false;
24701         break;
24702       }
24703     }
24704   }
24705
24706   if (!IsZext)
24707     return SDValue();
24708
24709   // Ok, perform the transformation - replace the shuffle with
24710   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24711   // (instead of undef) where the k elements come from the zero vector.
24712   SmallVector<int, 8> Mask;
24713   unsigned NumElems = SrcType.getVectorNumElements();
24714   for (unsigned i = 0; i < NumElems; ++i)
24715     if (i % ZextRatio)
24716       Mask.push_back(NumElems);
24717     else
24718       Mask.push_back(i / ZextRatio);
24719
24720   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24721     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24722   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24723 }
24724
24725 /// If both input operands of a logic op are being cast from floating point
24726 /// types, try to convert this into a floating point logic node to avoid
24727 /// unnecessary moves from SSE to integer registers.
24728 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
24729                                         const X86Subtarget *Subtarget) {
24730   unsigned FPOpcode = ISD::DELETED_NODE;
24731   if (N->getOpcode() == ISD::AND)
24732     FPOpcode = X86ISD::FAND;
24733   else if (N->getOpcode() == ISD::OR)
24734     FPOpcode = X86ISD::FOR;
24735   else if (N->getOpcode() == ISD::XOR)
24736     FPOpcode = X86ISD::FXOR;
24737
24738   assert(FPOpcode != ISD::DELETED_NODE &&
24739          "Unexpected input node for FP logic conversion");
24740
24741   EVT VT = N->getValueType(0);
24742   SDValue N0 = N->getOperand(0);
24743   SDValue N1 = N->getOperand(1);
24744   SDLoc DL(N);
24745   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24746       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24747        (Subtarget->hasSSE2() && VT == MVT::i64))) {
24748     SDValue N00 = N0.getOperand(0);
24749     SDValue N10 = N1.getOperand(0);
24750     EVT N00Type = N00.getValueType();
24751     EVT N10Type = N10.getValueType();
24752     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24753       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
24754       return DAG.getBitcast(VT, FPLogic);
24755     }
24756   }
24757   return SDValue();
24758 }
24759
24760 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24761                                  TargetLowering::DAGCombinerInfo &DCI,
24762                                  const X86Subtarget *Subtarget) {
24763   if (DCI.isBeforeLegalizeOps())
24764     return SDValue();
24765
24766   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24767     return Zext;
24768
24769   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24770     return R;
24771
24772   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24773     return FPLogic;
24774
24775   EVT VT = N->getValueType(0);
24776   SDValue N0 = N->getOperand(0);
24777   SDValue N1 = N->getOperand(1);
24778   SDLoc DL(N);
24779
24780   // Create BEXTR instructions
24781   // BEXTR is ((X >> imm) & (2**size-1))
24782   if (VT == MVT::i32 || VT == MVT::i64) {
24783     // Check for BEXTR.
24784     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24785         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24786       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24787       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24788       if (MaskNode && ShiftNode) {
24789         uint64_t Mask = MaskNode->getZExtValue();
24790         uint64_t Shift = ShiftNode->getZExtValue();
24791         if (isMask_64(Mask)) {
24792           uint64_t MaskSize = countPopulation(Mask);
24793           if (Shift + MaskSize <= VT.getSizeInBits())
24794             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24795                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24796                                                VT));
24797         }
24798       }
24799     } // BEXTR
24800
24801     return SDValue();
24802   }
24803
24804   // Want to form ANDNP nodes:
24805   // 1) In the hopes of then easily combining them with OR and AND nodes
24806   //    to form PBLEND/PSIGN.
24807   // 2) To match ANDN packed intrinsics
24808   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24809     return SDValue();
24810
24811   // Check LHS for vnot
24812   if (N0.getOpcode() == ISD::XOR &&
24813       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24814       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24815     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24816
24817   // Check RHS for vnot
24818   if (N1.getOpcode() == ISD::XOR &&
24819       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24820       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24821     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24822
24823   return SDValue();
24824 }
24825
24826 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24827                                 TargetLowering::DAGCombinerInfo &DCI,
24828                                 const X86Subtarget *Subtarget) {
24829   if (DCI.isBeforeLegalizeOps())
24830     return SDValue();
24831
24832   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24833     return R;
24834
24835   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
24836     return FPLogic;
24837
24838   SDValue N0 = N->getOperand(0);
24839   SDValue N1 = N->getOperand(1);
24840   EVT VT = N->getValueType(0);
24841
24842   // look for psign/blend
24843   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24844     if (!Subtarget->hasSSSE3() ||
24845         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24846       return SDValue();
24847
24848     // Canonicalize pandn to RHS
24849     if (N0.getOpcode() == X86ISD::ANDNP)
24850       std::swap(N0, N1);
24851     // or (and (m, y), (pandn m, x))
24852     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24853       SDValue Mask = N1.getOperand(0);
24854       SDValue X    = N1.getOperand(1);
24855       SDValue Y;
24856       if (N0.getOperand(0) == Mask)
24857         Y = N0.getOperand(1);
24858       if (N0.getOperand(1) == Mask)
24859         Y = N0.getOperand(0);
24860
24861       // Check to see if the mask appeared in both the AND and ANDNP and
24862       if (!Y.getNode())
24863         return SDValue();
24864
24865       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24866       // Look through mask bitcast.
24867       if (Mask.getOpcode() == ISD::BITCAST)
24868         Mask = Mask.getOperand(0);
24869       if (X.getOpcode() == ISD::BITCAST)
24870         X = X.getOperand(0);
24871       if (Y.getOpcode() == ISD::BITCAST)
24872         Y = Y.getOperand(0);
24873
24874       EVT MaskVT = Mask.getValueType();
24875
24876       // Validate that the Mask operand is a vector sra node.
24877       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24878       // there is no psrai.b
24879       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24880       unsigned SraAmt = ~0;
24881       if (Mask.getOpcode() == ISD::SRA) {
24882         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24883           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24884             SraAmt = AmtConst->getZExtValue();
24885       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24886         SDValue SraC = Mask.getOperand(1);
24887         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24888       }
24889       if ((SraAmt + 1) != EltBits)
24890         return SDValue();
24891
24892       SDLoc DL(N);
24893
24894       // Now we know we at least have a plendvb with the mask val.  See if
24895       // we can form a psignb/w/d.
24896       // psign = x.type == y.type == mask.type && y = sub(0, x);
24897       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24898           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24899           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24900         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24901                "Unsupported VT for PSIGN");
24902         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24903         return DAG.getBitcast(VT, Mask);
24904       }
24905       // PBLENDVB only available on SSE 4.1
24906       if (!Subtarget->hasSSE41())
24907         return SDValue();
24908
24909       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24910
24911       X = DAG.getBitcast(BlendVT, X);
24912       Y = DAG.getBitcast(BlendVT, Y);
24913       Mask = DAG.getBitcast(BlendVT, Mask);
24914       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24915       return DAG.getBitcast(VT, Mask);
24916     }
24917   }
24918
24919   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24920     return SDValue();
24921
24922   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24923   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24924
24925   // SHLD/SHRD instructions have lower register pressure, but on some
24926   // platforms they have higher latency than the equivalent
24927   // series of shifts/or that would otherwise be generated.
24928   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24929   // have higher latencies and we are not optimizing for size.
24930   if (!OptForSize && Subtarget->isSHLDSlow())
24931     return SDValue();
24932
24933   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24934     std::swap(N0, N1);
24935   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24936     return SDValue();
24937   if (!N0.hasOneUse() || !N1.hasOneUse())
24938     return SDValue();
24939
24940   SDValue ShAmt0 = N0.getOperand(1);
24941   if (ShAmt0.getValueType() != MVT::i8)
24942     return SDValue();
24943   SDValue ShAmt1 = N1.getOperand(1);
24944   if (ShAmt1.getValueType() != MVT::i8)
24945     return SDValue();
24946   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24947     ShAmt0 = ShAmt0.getOperand(0);
24948   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24949     ShAmt1 = ShAmt1.getOperand(0);
24950
24951   SDLoc DL(N);
24952   unsigned Opc = X86ISD::SHLD;
24953   SDValue Op0 = N0.getOperand(0);
24954   SDValue Op1 = N1.getOperand(0);
24955   if (ShAmt0.getOpcode() == ISD::SUB) {
24956     Opc = X86ISD::SHRD;
24957     std::swap(Op0, Op1);
24958     std::swap(ShAmt0, ShAmt1);
24959   }
24960
24961   unsigned Bits = VT.getSizeInBits();
24962   if (ShAmt1.getOpcode() == ISD::SUB) {
24963     SDValue Sum = ShAmt1.getOperand(0);
24964     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24965       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24966       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24967         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24968       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24969         return DAG.getNode(Opc, DL, VT,
24970                            Op0, Op1,
24971                            DAG.getNode(ISD::TRUNCATE, DL,
24972                                        MVT::i8, ShAmt0));
24973     }
24974   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24975     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24976     if (ShAmt0C &&
24977         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24978       return DAG.getNode(Opc, DL, VT,
24979                          N0.getOperand(0), N1.getOperand(0),
24980                          DAG.getNode(ISD::TRUNCATE, DL,
24981                                        MVT::i8, ShAmt0));
24982   }
24983
24984   return SDValue();
24985 }
24986
24987 // Generate NEG and CMOV for integer abs.
24988 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24989   EVT VT = N->getValueType(0);
24990
24991   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24992   // 8-bit integer abs to NEG and CMOV.
24993   if (VT.isInteger() && VT.getSizeInBits() == 8)
24994     return SDValue();
24995
24996   SDValue N0 = N->getOperand(0);
24997   SDValue N1 = N->getOperand(1);
24998   SDLoc DL(N);
24999
25000   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25001   // and change it to SUB and CMOV.
25002   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25003       N0.getOpcode() == ISD::ADD &&
25004       N0.getOperand(1) == N1 &&
25005       N1.getOpcode() == ISD::SRA &&
25006       N1.getOperand(0) == N0.getOperand(0))
25007     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25008       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25009         // Generate SUB & CMOV.
25010         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25011                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25012
25013         SDValue Ops[] = { N0.getOperand(0), Neg,
25014                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25015                           SDValue(Neg.getNode(), 1) };
25016         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25017       }
25018   return SDValue();
25019 }
25020
25021 // Try to turn tests against the signbit in the form of:
25022 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25023 // into:
25024 //   SETGT(X, -1)
25025 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25026   // This is only worth doing if the output type is i8.
25027   if (N->getValueType(0) != MVT::i8)
25028     return SDValue();
25029
25030   SDValue N0 = N->getOperand(0);
25031   SDValue N1 = N->getOperand(1);
25032
25033   // We should be performing an xor against a truncated shift.
25034   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25035     return SDValue();
25036
25037   // Make sure we are performing an xor against one.
25038   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
25039     return SDValue();
25040
25041   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25042   SDValue Shift = N0.getOperand(0);
25043   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25044     return SDValue();
25045
25046   // Make sure we are truncating from one of i16, i32 or i64.
25047   EVT ShiftTy = Shift.getValueType();
25048   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25049     return SDValue();
25050
25051   // Make sure the shift amount extracts the sign bit.
25052   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25053       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25054     return SDValue();
25055
25056   // Create a greater-than comparison against -1.
25057   // N.B. Using SETGE against 0 works but we want a canonical looking
25058   // comparison, using SETGT matches up with what TranslateX86CC.
25059   SDLoc DL(N);
25060   SDValue ShiftOp = Shift.getOperand(0);
25061   EVT ShiftOpTy = ShiftOp.getValueType();
25062   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25063                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25064   return Cond;
25065 }
25066
25067 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25068                                  TargetLowering::DAGCombinerInfo &DCI,
25069                                  const X86Subtarget *Subtarget) {
25070   if (DCI.isBeforeLegalizeOps())
25071     return SDValue();
25072
25073   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25074     return RV;
25075
25076   if (Subtarget->hasCMov())
25077     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25078       return RV;
25079
25080   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25081     return FPLogic;
25082
25083   return SDValue();
25084 }
25085
25086 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25087 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25088                                   TargetLowering::DAGCombinerInfo &DCI,
25089                                   const X86Subtarget *Subtarget) {
25090   LoadSDNode *Ld = cast<LoadSDNode>(N);
25091   EVT RegVT = Ld->getValueType(0);
25092   EVT MemVT = Ld->getMemoryVT();
25093   SDLoc dl(Ld);
25094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25095
25096   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25097   // into two 16-byte operations.
25098   ISD::LoadExtType Ext = Ld->getExtensionType();
25099   bool Fast;
25100   unsigned AddressSpace = Ld->getAddressSpace();
25101   unsigned Alignment = Ld->getAlignment();
25102   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25103       Ext == ISD::NON_EXTLOAD &&
25104       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25105                              AddressSpace, Alignment, &Fast) && !Fast) {
25106     unsigned NumElems = RegVT.getVectorNumElements();
25107     if (NumElems < 2)
25108       return SDValue();
25109
25110     SDValue Ptr = Ld->getBasePtr();
25111     SDValue Increment =
25112         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25113
25114     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25115                                   NumElems/2);
25116     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25117                                 Ld->getPointerInfo(), Ld->isVolatile(),
25118                                 Ld->isNonTemporal(), Ld->isInvariant(),
25119                                 Alignment);
25120     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25121     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25122                                 Ld->getPointerInfo(), Ld->isVolatile(),
25123                                 Ld->isNonTemporal(), Ld->isInvariant(),
25124                                 std::min(16U, Alignment));
25125     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25126                              Load1.getValue(1),
25127                              Load2.getValue(1));
25128
25129     SDValue NewVec = DAG.getUNDEF(RegVT);
25130     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25131     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25132     return DCI.CombineTo(N, NewVec, TF, true);
25133   }
25134
25135   return SDValue();
25136 }
25137
25138 /// PerformMLOADCombine - Resolve extending loads
25139 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25140                                    TargetLowering::DAGCombinerInfo &DCI,
25141                                    const X86Subtarget *Subtarget) {
25142   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25143   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25144     return SDValue();
25145
25146   EVT VT = Mld->getValueType(0);
25147   unsigned NumElems = VT.getVectorNumElements();
25148   EVT LdVT = Mld->getMemoryVT();
25149   SDLoc dl(Mld);
25150
25151   assert(LdVT != VT && "Cannot extend to the same type");
25152   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25153   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25154   // From, To sizes and ElemCount must be pow of two
25155   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25156     "Unexpected size for extending masked load");
25157
25158   unsigned SizeRatio  = ToSz / FromSz;
25159   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25160
25161   // Create a type on which we perform the shuffle
25162   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25163           LdVT.getScalarType(), NumElems*SizeRatio);
25164   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25165
25166   // Convert Src0 value
25167   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25168   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25169     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25170     for (unsigned i = 0; i != NumElems; ++i)
25171       ShuffleVec[i] = i * SizeRatio;
25172
25173     // Can't shuffle using an illegal type.
25174     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25175            "WideVecVT should be legal");
25176     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25177                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25178   }
25179   // Prepare the new mask
25180   SDValue NewMask;
25181   SDValue Mask = Mld->getMask();
25182   if (Mask.getValueType() == VT) {
25183     // Mask and original value have the same type
25184     NewMask = DAG.getBitcast(WideVecVT, Mask);
25185     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25186     for (unsigned i = 0; i != NumElems; ++i)
25187       ShuffleVec[i] = i * SizeRatio;
25188     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25189       ShuffleVec[i] = NumElems*SizeRatio;
25190     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25191                                    DAG.getConstant(0, dl, WideVecVT),
25192                                    &ShuffleVec[0]);
25193   }
25194   else {
25195     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25196     unsigned WidenNumElts = NumElems*SizeRatio;
25197     unsigned MaskNumElts = VT.getVectorNumElements();
25198     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25199                                      WidenNumElts);
25200
25201     unsigned NumConcat = WidenNumElts / MaskNumElts;
25202     SmallVector<SDValue, 16> Ops(NumConcat);
25203     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25204     Ops[0] = Mask;
25205     for (unsigned i = 1; i != NumConcat; ++i)
25206       Ops[i] = ZeroVal;
25207
25208     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25209   }
25210
25211   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25212                                      Mld->getBasePtr(), NewMask, WideSrc0,
25213                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25214                                      ISD::NON_EXTLOAD);
25215   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25216   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25217 }
25218 /// PerformMSTORECombine - Resolve truncating stores
25219 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25220                                     const X86Subtarget *Subtarget) {
25221   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25222   if (!Mst->isTruncatingStore())
25223     return SDValue();
25224
25225   EVT VT = Mst->getValue().getValueType();
25226   unsigned NumElems = VT.getVectorNumElements();
25227   EVT StVT = Mst->getMemoryVT();
25228   SDLoc dl(Mst);
25229
25230   assert(StVT != VT && "Cannot truncate to the same type");
25231   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25232   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25233
25234   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25235
25236   // The truncating store is legal in some cases. For example
25237   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25238   // are designated for truncate store.
25239   // In this case we don't need any further transformations.
25240   if (TLI.isTruncStoreLegal(VT, StVT))
25241     return SDValue();
25242
25243   // From, To sizes and ElemCount must be pow of two
25244   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25245     "Unexpected size for truncating masked store");
25246   // We are going to use the original vector elt for storing.
25247   // Accumulated smaller vector elements must be a multiple of the store size.
25248   assert (((NumElems * FromSz) % ToSz) == 0 &&
25249           "Unexpected ratio for truncating masked store");
25250
25251   unsigned SizeRatio  = FromSz / ToSz;
25252   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25253
25254   // Create a type on which we perform the shuffle
25255   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25256           StVT.getScalarType(), NumElems*SizeRatio);
25257
25258   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25259
25260   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25261   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25262   for (unsigned i = 0; i != NumElems; ++i)
25263     ShuffleVec[i] = i * SizeRatio;
25264
25265   // Can't shuffle using an illegal type.
25266   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25267          "WideVecVT should be legal");
25268
25269   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25270                                         DAG.getUNDEF(WideVecVT),
25271                                         &ShuffleVec[0]);
25272
25273   SDValue NewMask;
25274   SDValue Mask = Mst->getMask();
25275   if (Mask.getValueType() == VT) {
25276     // Mask and original value have the same type
25277     NewMask = DAG.getBitcast(WideVecVT, Mask);
25278     for (unsigned i = 0; i != NumElems; ++i)
25279       ShuffleVec[i] = i * SizeRatio;
25280     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25281       ShuffleVec[i] = NumElems*SizeRatio;
25282     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25283                                    DAG.getConstant(0, dl, WideVecVT),
25284                                    &ShuffleVec[0]);
25285   }
25286   else {
25287     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25288     unsigned WidenNumElts = NumElems*SizeRatio;
25289     unsigned MaskNumElts = VT.getVectorNumElements();
25290     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25291                                      WidenNumElts);
25292
25293     unsigned NumConcat = WidenNumElts / MaskNumElts;
25294     SmallVector<SDValue, 16> Ops(NumConcat);
25295     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25296     Ops[0] = Mask;
25297     for (unsigned i = 1; i != NumConcat; ++i)
25298       Ops[i] = ZeroVal;
25299
25300     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25301   }
25302
25303   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25304                             NewMask, StVT, Mst->getMemOperand(), false);
25305 }
25306 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25307 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25308                                    const X86Subtarget *Subtarget) {
25309   StoreSDNode *St = cast<StoreSDNode>(N);
25310   EVT VT = St->getValue().getValueType();
25311   EVT StVT = St->getMemoryVT();
25312   SDLoc dl(St);
25313   SDValue StoredVal = St->getOperand(1);
25314   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25315
25316   // If we are saving a concatenation of two XMM registers and 32-byte stores
25317   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25318   bool Fast;
25319   unsigned AddressSpace = St->getAddressSpace();
25320   unsigned Alignment = St->getAlignment();
25321   if (VT.is256BitVector() && StVT == VT &&
25322       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25323                              AddressSpace, Alignment, &Fast) && !Fast) {
25324     unsigned NumElems = VT.getVectorNumElements();
25325     if (NumElems < 2)
25326       return SDValue();
25327
25328     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25329     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25330
25331     SDValue Stride =
25332         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25333     SDValue Ptr0 = St->getBasePtr();
25334     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25335
25336     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25337                                 St->getPointerInfo(), St->isVolatile(),
25338                                 St->isNonTemporal(), Alignment);
25339     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25340                                 St->getPointerInfo(), St->isVolatile(),
25341                                 St->isNonTemporal(),
25342                                 std::min(16U, Alignment));
25343     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25344   }
25345
25346   // Optimize trunc store (of multiple scalars) to shuffle and store.
25347   // First, pack all of the elements in one place. Next, store to memory
25348   // in fewer chunks.
25349   if (St->isTruncatingStore() && VT.isVector()) {
25350     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25351     unsigned NumElems = VT.getVectorNumElements();
25352     assert(StVT != VT && "Cannot truncate to the same type");
25353     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25354     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25355
25356     // The truncating store is legal in some cases. For example
25357     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25358     // are designated for truncate store.
25359     // In this case we don't need any further transformations.
25360     if (TLI.isTruncStoreLegal(VT, StVT))
25361       return SDValue();
25362
25363     // From, To sizes and ElemCount must be pow of two
25364     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25365     // We are going to use the original vector elt for storing.
25366     // Accumulated smaller vector elements must be a multiple of the store size.
25367     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25368
25369     unsigned SizeRatio  = FromSz / ToSz;
25370
25371     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25372
25373     // Create a type on which we perform the shuffle
25374     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25375             StVT.getScalarType(), NumElems*SizeRatio);
25376
25377     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25378
25379     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25380     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25381     for (unsigned i = 0; i != NumElems; ++i)
25382       ShuffleVec[i] = i * SizeRatio;
25383
25384     // Can't shuffle using an illegal type.
25385     if (!TLI.isTypeLegal(WideVecVT))
25386       return SDValue();
25387
25388     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25389                                          DAG.getUNDEF(WideVecVT),
25390                                          &ShuffleVec[0]);
25391     // At this point all of the data is stored at the bottom of the
25392     // register. We now need to save it to mem.
25393
25394     // Find the largest store unit
25395     MVT StoreType = MVT::i8;
25396     for (MVT Tp : MVT::integer_valuetypes()) {
25397       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25398         StoreType = Tp;
25399     }
25400
25401     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25402     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25403         (64 <= NumElems * ToSz))
25404       StoreType = MVT::f64;
25405
25406     // Bitcast the original vector into a vector of store-size units
25407     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25408             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25409     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25410     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25411     SmallVector<SDValue, 8> Chains;
25412     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25413                                         TLI.getPointerTy(DAG.getDataLayout()));
25414     SDValue Ptr = St->getBasePtr();
25415
25416     // Perform one or more big stores into memory.
25417     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25418       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25419                                    StoreType, ShuffWide,
25420                                    DAG.getIntPtrConstant(i, dl));
25421       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25422                                 St->getPointerInfo(), St->isVolatile(),
25423                                 St->isNonTemporal(), St->getAlignment());
25424       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25425       Chains.push_back(Ch);
25426     }
25427
25428     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25429   }
25430
25431   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25432   // the FP state in cases where an emms may be missing.
25433   // A preferable solution to the general problem is to figure out the right
25434   // places to insert EMMS.  This qualifies as a quick hack.
25435
25436   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25437   if (VT.getSizeInBits() != 64)
25438     return SDValue();
25439
25440   const Function *F = DAG.getMachineFunction().getFunction();
25441   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25442   bool F64IsLegal =
25443       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25444   if ((VT.isVector() ||
25445        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25446       isa<LoadSDNode>(St->getValue()) &&
25447       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25448       St->getChain().hasOneUse() && !St->isVolatile()) {
25449     SDNode* LdVal = St->getValue().getNode();
25450     LoadSDNode *Ld = nullptr;
25451     int TokenFactorIndex = -1;
25452     SmallVector<SDValue, 8> Ops;
25453     SDNode* ChainVal = St->getChain().getNode();
25454     // Must be a store of a load.  We currently handle two cases:  the load
25455     // is a direct child, and it's under an intervening TokenFactor.  It is
25456     // possible to dig deeper under nested TokenFactors.
25457     if (ChainVal == LdVal)
25458       Ld = cast<LoadSDNode>(St->getChain());
25459     else if (St->getValue().hasOneUse() &&
25460              ChainVal->getOpcode() == ISD::TokenFactor) {
25461       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25462         if (ChainVal->getOperand(i).getNode() == LdVal) {
25463           TokenFactorIndex = i;
25464           Ld = cast<LoadSDNode>(St->getValue());
25465         } else
25466           Ops.push_back(ChainVal->getOperand(i));
25467       }
25468     }
25469
25470     if (!Ld || !ISD::isNormalLoad(Ld))
25471       return SDValue();
25472
25473     // If this is not the MMX case, i.e. we are just turning i64 load/store
25474     // into f64 load/store, avoid the transformation if there are multiple
25475     // uses of the loaded value.
25476     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25477       return SDValue();
25478
25479     SDLoc LdDL(Ld);
25480     SDLoc StDL(N);
25481     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25482     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25483     // pair instead.
25484     if (Subtarget->is64Bit() || F64IsLegal) {
25485       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25486       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25487                                   Ld->getPointerInfo(), Ld->isVolatile(),
25488                                   Ld->isNonTemporal(), Ld->isInvariant(),
25489                                   Ld->getAlignment());
25490       SDValue NewChain = NewLd.getValue(1);
25491       if (TokenFactorIndex != -1) {
25492         Ops.push_back(NewChain);
25493         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25494       }
25495       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25496                           St->getPointerInfo(),
25497                           St->isVolatile(), St->isNonTemporal(),
25498                           St->getAlignment());
25499     }
25500
25501     // Otherwise, lower to two pairs of 32-bit loads / stores.
25502     SDValue LoAddr = Ld->getBasePtr();
25503     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25504                                  DAG.getConstant(4, LdDL, MVT::i32));
25505
25506     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25507                                Ld->getPointerInfo(),
25508                                Ld->isVolatile(), Ld->isNonTemporal(),
25509                                Ld->isInvariant(), Ld->getAlignment());
25510     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25511                                Ld->getPointerInfo().getWithOffset(4),
25512                                Ld->isVolatile(), Ld->isNonTemporal(),
25513                                Ld->isInvariant(),
25514                                MinAlign(Ld->getAlignment(), 4));
25515
25516     SDValue NewChain = LoLd.getValue(1);
25517     if (TokenFactorIndex != -1) {
25518       Ops.push_back(LoLd);
25519       Ops.push_back(HiLd);
25520       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25521     }
25522
25523     LoAddr = St->getBasePtr();
25524     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25525                          DAG.getConstant(4, StDL, MVT::i32));
25526
25527     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25528                                 St->getPointerInfo(),
25529                                 St->isVolatile(), St->isNonTemporal(),
25530                                 St->getAlignment());
25531     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25532                                 St->getPointerInfo().getWithOffset(4),
25533                                 St->isVolatile(),
25534                                 St->isNonTemporal(),
25535                                 MinAlign(St->getAlignment(), 4));
25536     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25537   }
25538
25539   // This is similar to the above case, but here we handle a scalar 64-bit
25540   // integer store that is extracted from a vector on a 32-bit target.
25541   // If we have SSE2, then we can treat it like a floating-point double
25542   // to get past legalization. The execution dependencies fixup pass will
25543   // choose the optimal machine instruction for the store if this really is
25544   // an integer or v2f32 rather than an f64.
25545   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25546       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25547     SDValue OldExtract = St->getOperand(1);
25548     SDValue ExtOp0 = OldExtract.getOperand(0);
25549     unsigned VecSize = ExtOp0.getValueSizeInBits();
25550     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25551     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25552     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25553                                      BitCast, OldExtract.getOperand(1));
25554     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25555                         St->getPointerInfo(), St->isVolatile(),
25556                         St->isNonTemporal(), St->getAlignment());
25557   }
25558
25559   return SDValue();
25560 }
25561
25562 /// Return 'true' if this vector operation is "horizontal"
25563 /// and return the operands for the horizontal operation in LHS and RHS.  A
25564 /// horizontal operation performs the binary operation on successive elements
25565 /// of its first operand, then on successive elements of its second operand,
25566 /// returning the resulting values in a vector.  For example, if
25567 ///   A = < float a0, float a1, float a2, float a3 >
25568 /// and
25569 ///   B = < float b0, float b1, float b2, float b3 >
25570 /// then the result of doing a horizontal operation on A and B is
25571 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25572 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25573 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25574 /// set to A, RHS to B, and the routine returns 'true'.
25575 /// Note that the binary operation should have the property that if one of the
25576 /// operands is UNDEF then the result is UNDEF.
25577 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25578   // Look for the following pattern: if
25579   //   A = < float a0, float a1, float a2, float a3 >
25580   //   B = < float b0, float b1, float b2, float b3 >
25581   // and
25582   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25583   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25584   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25585   // which is A horizontal-op B.
25586
25587   // At least one of the operands should be a vector shuffle.
25588   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25589       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25590     return false;
25591
25592   MVT VT = LHS.getSimpleValueType();
25593
25594   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25595          "Unsupported vector type for horizontal add/sub");
25596
25597   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25598   // operate independently on 128-bit lanes.
25599   unsigned NumElts = VT.getVectorNumElements();
25600   unsigned NumLanes = VT.getSizeInBits()/128;
25601   unsigned NumLaneElts = NumElts / NumLanes;
25602   assert((NumLaneElts % 2 == 0) &&
25603          "Vector type should have an even number of elements in each lane");
25604   unsigned HalfLaneElts = NumLaneElts/2;
25605
25606   // View LHS in the form
25607   //   LHS = VECTOR_SHUFFLE A, B, LMask
25608   // If LHS is not a shuffle then pretend it is the shuffle
25609   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25610   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25611   // type VT.
25612   SDValue A, B;
25613   SmallVector<int, 16> LMask(NumElts);
25614   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25615     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25616       A = LHS.getOperand(0);
25617     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25618       B = LHS.getOperand(1);
25619     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25620     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25621   } else {
25622     if (LHS.getOpcode() != ISD::UNDEF)
25623       A = LHS;
25624     for (unsigned i = 0; i != NumElts; ++i)
25625       LMask[i] = i;
25626   }
25627
25628   // Likewise, view RHS in the form
25629   //   RHS = VECTOR_SHUFFLE C, D, RMask
25630   SDValue C, D;
25631   SmallVector<int, 16> RMask(NumElts);
25632   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25633     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25634       C = RHS.getOperand(0);
25635     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25636       D = RHS.getOperand(1);
25637     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25638     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25639   } else {
25640     if (RHS.getOpcode() != ISD::UNDEF)
25641       C = RHS;
25642     for (unsigned i = 0; i != NumElts; ++i)
25643       RMask[i] = i;
25644   }
25645
25646   // Check that the shuffles are both shuffling the same vectors.
25647   if (!(A == C && B == D) && !(A == D && B == C))
25648     return false;
25649
25650   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25651   if (!A.getNode() && !B.getNode())
25652     return false;
25653
25654   // If A and B occur in reverse order in RHS, then "swap" them (which means
25655   // rewriting the mask).
25656   if (A != C)
25657     ShuffleVectorSDNode::commuteMask(RMask);
25658
25659   // At this point LHS and RHS are equivalent to
25660   //   LHS = VECTOR_SHUFFLE A, B, LMask
25661   //   RHS = VECTOR_SHUFFLE A, B, RMask
25662   // Check that the masks correspond to performing a horizontal operation.
25663   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25664     for (unsigned i = 0; i != NumLaneElts; ++i) {
25665       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25666
25667       // Ignore any UNDEF components.
25668       if (LIdx < 0 || RIdx < 0 ||
25669           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25670           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25671         continue;
25672
25673       // Check that successive elements are being operated on.  If not, this is
25674       // not a horizontal operation.
25675       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25676       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25677       if (!(LIdx == Index && RIdx == Index + 1) &&
25678           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25679         return false;
25680     }
25681   }
25682
25683   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25684   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25685   return true;
25686 }
25687
25688 /// Do target-specific dag combines on floating point adds.
25689 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25690                                   const X86Subtarget *Subtarget) {
25691   EVT VT = N->getValueType(0);
25692   SDValue LHS = N->getOperand(0);
25693   SDValue RHS = N->getOperand(1);
25694
25695   // Try to synthesize horizontal adds from adds of shuffles.
25696   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25697        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25698       isHorizontalBinOp(LHS, RHS, true))
25699     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25700   return SDValue();
25701 }
25702
25703 /// Do target-specific dag combines on floating point subs.
25704 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25705                                   const X86Subtarget *Subtarget) {
25706   EVT VT = N->getValueType(0);
25707   SDValue LHS = N->getOperand(0);
25708   SDValue RHS = N->getOperand(1);
25709
25710   // Try to synthesize horizontal subs from subs of shuffles.
25711   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25712        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25713       isHorizontalBinOp(LHS, RHS, false))
25714     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25715   return SDValue();
25716 }
25717
25718 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25719 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25720                                  const X86Subtarget *Subtarget) {
25721   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25722
25723   // F[X]OR(0.0, x) -> x
25724   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25725     if (C->getValueAPF().isPosZero())
25726       return N->getOperand(1);
25727
25728   // F[X]OR(x, 0.0) -> x
25729   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25730     if (C->getValueAPF().isPosZero())
25731       return N->getOperand(0);
25732
25733   EVT VT = N->getValueType(0);
25734   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25735     SDLoc dl(N);
25736     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25737     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25738
25739     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25740     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25741     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25742     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25743     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25744   }
25745   return SDValue();
25746 }
25747
25748 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25749 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25750   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25751
25752   // Only perform optimizations if UnsafeMath is used.
25753   if (!DAG.getTarget().Options.UnsafeFPMath)
25754     return SDValue();
25755
25756   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25757   // into FMINC and FMAXC, which are Commutative operations.
25758   unsigned NewOp = 0;
25759   switch (N->getOpcode()) {
25760     default: llvm_unreachable("unknown opcode");
25761     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25762     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25763   }
25764
25765   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25766                      N->getOperand(0), N->getOperand(1));
25767 }
25768
25769 /// Do target-specific dag combines on X86ISD::FAND nodes.
25770 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25771   // FAND(0.0, x) -> 0.0
25772   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25773     if (C->getValueAPF().isPosZero())
25774       return N->getOperand(0);
25775
25776   // FAND(x, 0.0) -> 0.0
25777   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25778     if (C->getValueAPF().isPosZero())
25779       return N->getOperand(1);
25780
25781   return SDValue();
25782 }
25783
25784 /// Do target-specific dag combines on X86ISD::FANDN nodes
25785 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25786   // FANDN(0.0, x) -> x
25787   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25788     if (C->getValueAPF().isPosZero())
25789       return N->getOperand(1);
25790
25791   // FANDN(x, 0.0) -> 0.0
25792   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25793     if (C->getValueAPF().isPosZero())
25794       return N->getOperand(1);
25795
25796   return SDValue();
25797 }
25798
25799 static SDValue PerformBTCombine(SDNode *N,
25800                                 SelectionDAG &DAG,
25801                                 TargetLowering::DAGCombinerInfo &DCI) {
25802   // BT ignores high bits in the bit index operand.
25803   SDValue Op1 = N->getOperand(1);
25804   if (Op1.hasOneUse()) {
25805     unsigned BitWidth = Op1.getValueSizeInBits();
25806     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25807     APInt KnownZero, KnownOne;
25808     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25809                                           !DCI.isBeforeLegalizeOps());
25810     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25811     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25812         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25813       DCI.CommitTargetLoweringOpt(TLO);
25814   }
25815   return SDValue();
25816 }
25817
25818 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25819   SDValue Op = N->getOperand(0);
25820   if (Op.getOpcode() == ISD::BITCAST)
25821     Op = Op.getOperand(0);
25822   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25823   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25824       VT.getVectorElementType().getSizeInBits() ==
25825       OpVT.getVectorElementType().getSizeInBits()) {
25826     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25827   }
25828   return SDValue();
25829 }
25830
25831 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25832                                                const X86Subtarget *Subtarget) {
25833   EVT VT = N->getValueType(0);
25834   if (!VT.isVector())
25835     return SDValue();
25836
25837   SDValue N0 = N->getOperand(0);
25838   SDValue N1 = N->getOperand(1);
25839   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25840   SDLoc dl(N);
25841
25842   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25843   // both SSE and AVX2 since there is no sign-extended shift right
25844   // operation on a vector with 64-bit elements.
25845   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25846   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25847   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25848       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25849     SDValue N00 = N0.getOperand(0);
25850
25851     // EXTLOAD has a better solution on AVX2,
25852     // it may be replaced with X86ISD::VSEXT node.
25853     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25854       if (!ISD::isNormalLoad(N00.getNode()))
25855         return SDValue();
25856
25857     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25858         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25859                                   N00, N1);
25860       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25861     }
25862   }
25863   return SDValue();
25864 }
25865
25866 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
25867 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
25868 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
25869 /// eliminate extend, add, and shift instructions.
25870 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
25871                                        const X86Subtarget *Subtarget) {
25872   // TODO: This should be valid for other integer types.
25873   EVT VT = Sext->getValueType(0);
25874   if (VT != MVT::i64)
25875     return SDValue();
25876
25877   // We need an 'add nsw' feeding into the 'sext'.
25878   SDValue Add = Sext->getOperand(0);
25879   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
25880     return SDValue();
25881
25882   // Having a constant operand to the 'add' ensures that we are not increasing
25883   // the instruction count because the constant is extended for free below.
25884   // A constant operand can also become the displacement field of an LEA.
25885   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
25886   if (!AddOp1)
25887     return SDValue();
25888
25889   // Don't make the 'add' bigger if there's no hope of combining it with some
25890   // other 'add' or 'shl' instruction.
25891   // TODO: It may be profitable to generate simpler LEA instructions in place
25892   // of single 'add' instructions, but the cost model for selecting an LEA
25893   // currently has a high threshold.
25894   bool HasLEAPotential = false;
25895   for (auto *User : Sext->uses()) {
25896     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
25897       HasLEAPotential = true;
25898       break;
25899     }
25900   }
25901   if (!HasLEAPotential)
25902     return SDValue();
25903
25904   // Everything looks good, so pull the 'sext' ahead of the 'add'.
25905   int64_t AddConstant = AddOp1->getSExtValue();
25906   SDValue AddOp0 = Add.getOperand(0);
25907   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
25908   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
25909
25910   // The wider add is guaranteed to not wrap because both operands are
25911   // sign-extended.
25912   SDNodeFlags Flags;
25913   Flags.setNoSignedWrap(true);
25914   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
25915 }
25916
25917 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25918                                   TargetLowering::DAGCombinerInfo &DCI,
25919                                   const X86Subtarget *Subtarget) {
25920   SDValue N0 = N->getOperand(0);
25921   EVT VT = N->getValueType(0);
25922   EVT SVT = VT.getScalarType();
25923   EVT InVT = N0.getValueType();
25924   EVT InSVT = InVT.getScalarType();
25925   SDLoc DL(N);
25926
25927   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25928   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25929   // This exposes the sext to the sdivrem lowering, so that it directly extends
25930   // from AH (which we otherwise need to do contortions to access).
25931   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25932       InVT == MVT::i8 && VT == MVT::i32) {
25933     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25934     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25935                             N0.getOperand(0), N0.getOperand(1));
25936     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25937     return R.getValue(1);
25938   }
25939
25940   if (!DCI.isBeforeLegalizeOps()) {
25941     if (InVT == MVT::i1) {
25942       SDValue Zero = DAG.getConstant(0, DL, VT);
25943       SDValue AllOnes =
25944         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25945       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25946     }
25947     return SDValue();
25948   }
25949
25950   if (VT.isVector() && Subtarget->hasSSE2()) {
25951     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25952       EVT InVT = N.getValueType();
25953       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25954                                    Size / InVT.getScalarSizeInBits());
25955       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25956                                     DAG.getUNDEF(InVT));
25957       Opnds[0] = N;
25958       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25959     };
25960
25961     // If target-size is less than 128-bits, extend to a type that would extend
25962     // to 128 bits, extend that and extract the original target vector.
25963     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25964         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25965         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25966       unsigned Scale = 128 / VT.getSizeInBits();
25967       EVT ExVT =
25968           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25969       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25970       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25971       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25972                          DAG.getIntPtrConstant(0, DL));
25973     }
25974
25975     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25976     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25977     if (VT.getSizeInBits() == 128 &&
25978         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25979         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25980       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25981       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25982     }
25983
25984     // On pre-AVX2 targets, split into 128-bit nodes of
25985     // ISD::SIGN_EXTEND_VECTOR_INREG.
25986     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25987         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25988         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25989       unsigned NumVecs = VT.getSizeInBits() / 128;
25990       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25991       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25992       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25993
25994       SmallVector<SDValue, 8> Opnds;
25995       for (unsigned i = 0, Offset = 0; i != NumVecs;
25996            ++i, Offset += NumSubElts) {
25997         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25998                                      DAG.getIntPtrConstant(Offset, DL));
25999         SrcVec = ExtendVecSize(DL, SrcVec, 128);
26000         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26001         Opnds.push_back(SrcVec);
26002       }
26003       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26004     }
26005   }
26006
26007   if (Subtarget->hasAVX() && VT.isVector() && VT.getSizeInBits() == 256)
26008     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26009       return R;
26010
26011   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26012     return NewAdd;
26013
26014   return SDValue();
26015 }
26016
26017 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26018                                  const X86Subtarget* Subtarget) {
26019   SDLoc dl(N);
26020   EVT VT = N->getValueType(0);
26021
26022   // Let legalize expand this if it isn't a legal type yet.
26023   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26024     return SDValue();
26025
26026   EVT ScalarVT = VT.getScalarType();
26027   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
26028       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
26029        !Subtarget->hasAVX512()))
26030     return SDValue();
26031
26032   SDValue A = N->getOperand(0);
26033   SDValue B = N->getOperand(1);
26034   SDValue C = N->getOperand(2);
26035
26036   bool NegA = (A.getOpcode() == ISD::FNEG);
26037   bool NegB = (B.getOpcode() == ISD::FNEG);
26038   bool NegC = (C.getOpcode() == ISD::FNEG);
26039
26040   // Negative multiplication when NegA xor NegB
26041   bool NegMul = (NegA != NegB);
26042   if (NegA)
26043     A = A.getOperand(0);
26044   if (NegB)
26045     B = B.getOperand(0);
26046   if (NegC)
26047     C = C.getOperand(0);
26048
26049   unsigned Opcode;
26050   if (!NegMul)
26051     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26052   else
26053     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26054
26055   return DAG.getNode(Opcode, dl, VT, A, B, C);
26056 }
26057
26058 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26059                                   TargetLowering::DAGCombinerInfo &DCI,
26060                                   const X86Subtarget *Subtarget) {
26061   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
26062   //           (and (i32 x86isd::setcc_carry), 1)
26063   // This eliminates the zext. This transformation is necessary because
26064   // ISD::SETCC is always legalized to i8.
26065   SDLoc dl(N);
26066   SDValue N0 = N->getOperand(0);
26067   EVT VT = N->getValueType(0);
26068
26069   if (N0.getOpcode() == ISD::AND &&
26070       N0.hasOneUse() &&
26071       N0.getOperand(0).hasOneUse()) {
26072     SDValue N00 = N0.getOperand(0);
26073     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26074       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
26075       if (!C || C->getZExtValue() != 1)
26076         return SDValue();
26077       return DAG.getNode(ISD::AND, dl, VT,
26078                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26079                                      N00.getOperand(0), N00.getOperand(1)),
26080                          DAG.getConstant(1, dl, VT));
26081     }
26082   }
26083
26084   if (N0.getOpcode() == ISD::TRUNCATE &&
26085       N0.hasOneUse() &&
26086       N0.getOperand(0).hasOneUse()) {
26087     SDValue N00 = N0.getOperand(0);
26088     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26089       return DAG.getNode(ISD::AND, dl, VT,
26090                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26091                                      N00.getOperand(0), N00.getOperand(1)),
26092                          DAG.getConstant(1, dl, VT));
26093     }
26094   }
26095
26096   if (VT.is256BitVector())
26097     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26098       return R;
26099
26100   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26101   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26102   // This exposes the zext to the udivrem lowering, so that it directly extends
26103   // from AH (which we otherwise need to do contortions to access).
26104   if (N0.getOpcode() == ISD::UDIVREM &&
26105       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26106       (VT == MVT::i32 || VT == MVT::i64)) {
26107     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26108     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26109                             N0.getOperand(0), N0.getOperand(1));
26110     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26111     return R.getValue(1);
26112   }
26113
26114   return SDValue();
26115 }
26116
26117 // Optimize x == -y --> x+y == 0
26118 //          x != -y --> x+y != 0
26119 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26120                                       const X86Subtarget* Subtarget) {
26121   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26122   SDValue LHS = N->getOperand(0);
26123   SDValue RHS = N->getOperand(1);
26124   EVT VT = N->getValueType(0);
26125   SDLoc DL(N);
26126
26127   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26128     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26129       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26130         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26131                                    LHS.getOperand(1));
26132         return DAG.getSetCC(DL, N->getValueType(0), addV,
26133                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26134       }
26135   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26136     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26137       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26138         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26139                                    RHS.getOperand(1));
26140         return DAG.getSetCC(DL, N->getValueType(0), addV,
26141                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26142       }
26143
26144   if (VT.getScalarType() == MVT::i1 &&
26145       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26146     bool IsSEXT0 =
26147         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26148         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26149     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26150
26151     if (!IsSEXT0 || !IsVZero1) {
26152       // Swap the operands and update the condition code.
26153       std::swap(LHS, RHS);
26154       CC = ISD::getSetCCSwappedOperands(CC);
26155
26156       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26157                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26158       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26159     }
26160
26161     if (IsSEXT0 && IsVZero1) {
26162       assert(VT == LHS.getOperand(0).getValueType() &&
26163              "Uexpected operand type");
26164       if (CC == ISD::SETGT)
26165         return DAG.getConstant(0, DL, VT);
26166       if (CC == ISD::SETLE)
26167         return DAG.getConstant(1, DL, VT);
26168       if (CC == ISD::SETEQ || CC == ISD::SETGE)
26169         return DAG.getNOT(DL, LHS.getOperand(0), VT);
26170
26171       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26172              "Unexpected condition code!");
26173       return LHS.getOperand(0);
26174     }
26175   }
26176
26177   return SDValue();
26178 }
26179
26180 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
26181                                          SelectionDAG &DAG) {
26182   SDLoc dl(Load);
26183   MVT VT = Load->getSimpleValueType(0);
26184   MVT EVT = VT.getVectorElementType();
26185   SDValue Addr = Load->getOperand(1);
26186   SDValue NewAddr = DAG.getNode(
26187       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
26188       DAG.getConstant(Index * EVT.getStoreSize(), dl,
26189                       Addr.getSimpleValueType()));
26190
26191   SDValue NewLoad =
26192       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
26193                   DAG.getMachineFunction().getMachineMemOperand(
26194                       Load->getMemOperand(), 0, EVT.getStoreSize()));
26195   return NewLoad;
26196 }
26197
26198 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
26199                                       const X86Subtarget *Subtarget) {
26200   SDLoc dl(N);
26201   MVT VT = N->getOperand(1)->getSimpleValueType(0);
26202   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
26203          "X86insertps is only defined for v4x32");
26204
26205   SDValue Ld = N->getOperand(1);
26206   if (MayFoldLoad(Ld)) {
26207     // Extract the countS bits from the immediate so we can get the proper
26208     // address when narrowing the vector load to a specific element.
26209     // When the second source op is a memory address, insertps doesn't use
26210     // countS and just gets an f32 from that address.
26211     unsigned DestIndex =
26212         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
26213
26214     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
26215
26216     // Create this as a scalar to vector to match the instruction pattern.
26217     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
26218     // countS bits are ignored when loading from memory on insertps, which
26219     // means we don't need to explicitly set them to 0.
26220     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
26221                        LoadScalarToVector, N->getOperand(2));
26222   }
26223   return SDValue();
26224 }
26225
26226 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26227   SDValue V0 = N->getOperand(0);
26228   SDValue V1 = N->getOperand(1);
26229   SDLoc DL(N);
26230   EVT VT = N->getValueType(0);
26231
26232   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26233   // operands and changing the mask to 1. This saves us a bunch of
26234   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26235   // x86InstrInfo knows how to commute this back after instruction selection
26236   // if it would help register allocation.
26237
26238   // TODO: If optimizing for size or a processor that doesn't suffer from
26239   // partial register update stalls, this should be transformed into a MOVSD
26240   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26241
26242   if (VT == MVT::v2f64)
26243     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26244       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26245         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26246         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26247       }
26248
26249   return SDValue();
26250 }
26251
26252 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26253 // as "sbb reg,reg", since it can be extended without zext and produces
26254 // an all-ones bit which is more useful than 0/1 in some cases.
26255 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26256                                MVT VT) {
26257   if (VT == MVT::i8)
26258     return DAG.getNode(ISD::AND, DL, VT,
26259                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26260                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
26261                                    EFLAGS),
26262                        DAG.getConstant(1, DL, VT));
26263   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26264   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26265                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26266                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
26267                                  EFLAGS));
26268 }
26269
26270 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26271 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26272                                    TargetLowering::DAGCombinerInfo &DCI,
26273                                    const X86Subtarget *Subtarget) {
26274   SDLoc DL(N);
26275   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26276   SDValue EFLAGS = N->getOperand(1);
26277
26278   if (CC == X86::COND_A) {
26279     // Try to convert COND_A into COND_B in an attempt to facilitate
26280     // materializing "setb reg".
26281     //
26282     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26283     // cannot take an immediate as its first operand.
26284     //
26285     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26286         EFLAGS.getValueType().isInteger() &&
26287         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26288       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26289                                    EFLAGS.getNode()->getVTList(),
26290                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26291       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26292       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26293     }
26294   }
26295
26296   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26297   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26298   // cases.
26299   if (CC == X86::COND_B)
26300     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26301
26302   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26303     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26304     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26305   }
26306
26307   return SDValue();
26308 }
26309
26310 // Optimize branch condition evaluation.
26311 //
26312 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26313                                     TargetLowering::DAGCombinerInfo &DCI,
26314                                     const X86Subtarget *Subtarget) {
26315   SDLoc DL(N);
26316   SDValue Chain = N->getOperand(0);
26317   SDValue Dest = N->getOperand(1);
26318   SDValue EFLAGS = N->getOperand(3);
26319   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26320
26321   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26322     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26323     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26324                        Flags);
26325   }
26326
26327   return SDValue();
26328 }
26329
26330 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26331                                                          SelectionDAG &DAG) {
26332   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26333   // optimize away operation when it's from a constant.
26334   //
26335   // The general transformation is:
26336   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26337   //       AND(VECTOR_CMP(x,y), constant2)
26338   //    constant2 = UNARYOP(constant)
26339
26340   // Early exit if this isn't a vector operation, the operand of the
26341   // unary operation isn't a bitwise AND, or if the sizes of the operations
26342   // aren't the same.
26343   EVT VT = N->getValueType(0);
26344   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26345       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26346       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26347     return SDValue();
26348
26349   // Now check that the other operand of the AND is a constant. We could
26350   // make the transformation for non-constant splats as well, but it's unclear
26351   // that would be a benefit as it would not eliminate any operations, just
26352   // perform one more step in scalar code before moving to the vector unit.
26353   if (BuildVectorSDNode *BV =
26354           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26355     // Bail out if the vector isn't a constant.
26356     if (!BV->isConstant())
26357       return SDValue();
26358
26359     // Everything checks out. Build up the new and improved node.
26360     SDLoc DL(N);
26361     EVT IntVT = BV->getValueType(0);
26362     // Create a new constant of the appropriate type for the transformed
26363     // DAG.
26364     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26365     // The AND node needs bitcasts to/from an integer vector type around it.
26366     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26367     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26368                                  N->getOperand(0)->getOperand(0), MaskConst);
26369     SDValue Res = DAG.getBitcast(VT, NewAnd);
26370     return Res;
26371   }
26372
26373   return SDValue();
26374 }
26375
26376 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26377                                         const X86Subtarget *Subtarget) {
26378   SDValue Op0 = N->getOperand(0);
26379   EVT VT = N->getValueType(0);
26380   EVT InVT = Op0.getValueType();
26381   EVT InSVT = InVT.getScalarType();
26382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26383
26384   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26385   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26386   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26387     SDLoc dl(N);
26388     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26389                                  InVT.getVectorNumElements());
26390     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26391
26392     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26393       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26394
26395     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26396   }
26397
26398   return SDValue();
26399 }
26400
26401 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26402                                         const X86Subtarget *Subtarget) {
26403   // First try to optimize away the conversion entirely when it's
26404   // conditionally from a constant. Vectors only.
26405   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26406     return Res;
26407
26408   // Now move on to more general possibilities.
26409   SDValue Op0 = N->getOperand(0);
26410   EVT VT = N->getValueType(0);
26411   EVT InVT = Op0.getValueType();
26412   EVT InSVT = InVT.getScalarType();
26413
26414   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26415   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26416   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26417     SDLoc dl(N);
26418     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26419                                  InVT.getVectorNumElements());
26420     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26421     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26422   }
26423
26424   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26425   // a 32-bit target where SSE doesn't support i64->FP operations.
26426   if (Op0.getOpcode() == ISD::LOAD) {
26427     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26428     EVT LdVT = Ld->getValueType(0);
26429
26430     // This transformation is not supported if the result type is f16
26431     if (VT == MVT::f16)
26432       return SDValue();
26433
26434     if (!Ld->isVolatile() && !VT.isVector() &&
26435         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26436         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26437       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26438           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26439       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26440       return FILDChain;
26441     }
26442   }
26443   return SDValue();
26444 }
26445
26446 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26447 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26448                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26449   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26450   // the result is either zero or one (depending on the input carry bit).
26451   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26452   if (X86::isZeroNode(N->getOperand(0)) &&
26453       X86::isZeroNode(N->getOperand(1)) &&
26454       // We don't have a good way to replace an EFLAGS use, so only do this when
26455       // dead right now.
26456       SDValue(N, 1).use_empty()) {
26457     SDLoc DL(N);
26458     EVT VT = N->getValueType(0);
26459     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26460     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26461                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26462                                            DAG.getConstant(X86::COND_B, DL,
26463                                                            MVT::i8),
26464                                            N->getOperand(2)),
26465                                DAG.getConstant(1, DL, VT));
26466     return DCI.CombineTo(N, Res1, CarryOut);
26467   }
26468
26469   return SDValue();
26470 }
26471
26472 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26473 //      (add Y, (setne X, 0)) -> sbb -1, Y
26474 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26475 //      (sub (setne X, 0), Y) -> adc -1, Y
26476 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26477   SDLoc DL(N);
26478
26479   // Look through ZExts.
26480   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26481   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26482     return SDValue();
26483
26484   SDValue SetCC = Ext.getOperand(0);
26485   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26486     return SDValue();
26487
26488   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26489   if (CC != X86::COND_E && CC != X86::COND_NE)
26490     return SDValue();
26491
26492   SDValue Cmp = SetCC.getOperand(1);
26493   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26494       !X86::isZeroNode(Cmp.getOperand(1)) ||
26495       !Cmp.getOperand(0).getValueType().isInteger())
26496     return SDValue();
26497
26498   SDValue CmpOp0 = Cmp.getOperand(0);
26499   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26500                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26501
26502   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26503   if (CC == X86::COND_NE)
26504     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26505                        DL, OtherVal.getValueType(), OtherVal,
26506                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26507                        NewCmp);
26508   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26509                      DL, OtherVal.getValueType(), OtherVal,
26510                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26511 }
26512
26513 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26514 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26515                                  const X86Subtarget *Subtarget) {
26516   EVT VT = N->getValueType(0);
26517   SDValue Op0 = N->getOperand(0);
26518   SDValue Op1 = N->getOperand(1);
26519
26520   // Try to synthesize horizontal adds from adds of shuffles.
26521   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26522        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26523       isHorizontalBinOp(Op0, Op1, true))
26524     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26525
26526   return OptimizeConditionalInDecrement(N, DAG);
26527 }
26528
26529 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26530                                  const X86Subtarget *Subtarget) {
26531   SDValue Op0 = N->getOperand(0);
26532   SDValue Op1 = N->getOperand(1);
26533
26534   // X86 can't encode an immediate LHS of a sub. See if we can push the
26535   // negation into a preceding instruction.
26536   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26537     // If the RHS of the sub is a XOR with one use and a constant, invert the
26538     // immediate. Then add one to the LHS of the sub so we can turn
26539     // X-Y -> X+~Y+1, saving one register.
26540     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26541         isa<ConstantSDNode>(Op1.getOperand(1))) {
26542       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26543       EVT VT = Op0.getValueType();
26544       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26545                                    Op1.getOperand(0),
26546                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26547       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26548                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26549     }
26550   }
26551
26552   // Try to synthesize horizontal adds from adds of shuffles.
26553   EVT VT = N->getValueType(0);
26554   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26555        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26556       isHorizontalBinOp(Op0, Op1, true))
26557     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26558
26559   return OptimizeConditionalInDecrement(N, DAG);
26560 }
26561
26562 /// performVZEXTCombine - Performs build vector combines
26563 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26564                                    TargetLowering::DAGCombinerInfo &DCI,
26565                                    const X86Subtarget *Subtarget) {
26566   SDLoc DL(N);
26567   MVT VT = N->getSimpleValueType(0);
26568   SDValue Op = N->getOperand(0);
26569   MVT OpVT = Op.getSimpleValueType();
26570   MVT OpEltVT = OpVT.getVectorElementType();
26571   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26572
26573   // (vzext (bitcast (vzext (x)) -> (vzext x)
26574   SDValue V = Op;
26575   while (V.getOpcode() == ISD::BITCAST)
26576     V = V.getOperand(0);
26577
26578   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26579     MVT InnerVT = V.getSimpleValueType();
26580     MVT InnerEltVT = InnerVT.getVectorElementType();
26581
26582     // If the element sizes match exactly, we can just do one larger vzext. This
26583     // is always an exact type match as vzext operates on integer types.
26584     if (OpEltVT == InnerEltVT) {
26585       assert(OpVT == InnerVT && "Types must match for vzext!");
26586       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26587     }
26588
26589     // The only other way we can combine them is if only a single element of the
26590     // inner vzext is used in the input to the outer vzext.
26591     if (InnerEltVT.getSizeInBits() < InputBits)
26592       return SDValue();
26593
26594     // In this case, the inner vzext is completely dead because we're going to
26595     // only look at bits inside of the low element. Just do the outer vzext on
26596     // a bitcast of the input to the inner.
26597     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26598   }
26599
26600   // Check if we can bypass extracting and re-inserting an element of an input
26601   // vector. Essentially:
26602   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26603   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26604       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26605       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26606     SDValue ExtractedV = V.getOperand(0);
26607     SDValue OrigV = ExtractedV.getOperand(0);
26608     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26609       if (ExtractIdx->getZExtValue() == 0) {
26610         MVT OrigVT = OrigV.getSimpleValueType();
26611         // Extract a subvector if necessary...
26612         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26613           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26614           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26615                                     OrigVT.getVectorNumElements() / Ratio);
26616           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26617                               DAG.getIntPtrConstant(0, DL));
26618         }
26619         Op = DAG.getBitcast(OpVT, OrigV);
26620         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26621       }
26622   }
26623
26624   return SDValue();
26625 }
26626
26627 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26628                                              DAGCombinerInfo &DCI) const {
26629   SelectionDAG &DAG = DCI.DAG;
26630   switch (N->getOpcode()) {
26631   default: break;
26632   case ISD::EXTRACT_VECTOR_ELT:
26633     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26634   case ISD::VSELECT:
26635   case ISD::SELECT:
26636   case X86ISD::SHRUNKBLEND:
26637     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26638   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26639   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26640   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26641   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26642   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26643   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26644   case ISD::SHL:
26645   case ISD::SRA:
26646   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26647   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26648   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26649   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26650   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26651   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26652   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26653   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26654   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26655   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26656   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26657   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26658   case X86ISD::FXOR:
26659   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26660   case X86ISD::FMIN:
26661   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26662   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26663   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26664   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26665   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26666   case ISD::ANY_EXTEND:
26667   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26668   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26669   case ISD::SIGN_EXTEND_INREG:
26670     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26671   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26672   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26673   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26674   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26675   case X86ISD::SHUFP:       // Handle all target specific shuffles
26676   case X86ISD::PALIGNR:
26677   case X86ISD::UNPCKH:
26678   case X86ISD::UNPCKL:
26679   case X86ISD::MOVHLPS:
26680   case X86ISD::MOVLHPS:
26681   case X86ISD::PSHUFB:
26682   case X86ISD::PSHUFD:
26683   case X86ISD::PSHUFHW:
26684   case X86ISD::PSHUFLW:
26685   case X86ISD::MOVSS:
26686   case X86ISD::MOVSD:
26687   case X86ISD::VPERMILPI:
26688   case X86ISD::VPERM2X128:
26689   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26690   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26691   case X86ISD::INSERTPS: {
26692     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26693       return PerformINSERTPSCombine(N, DAG, Subtarget);
26694     break;
26695   }
26696   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26697   }
26698
26699   return SDValue();
26700 }
26701
26702 /// isTypeDesirableForOp - Return true if the target has native support for
26703 /// the specified value type and it is 'desirable' to use the type for the
26704 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26705 /// instruction encodings are longer and some i16 instructions are slow.
26706 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26707   if (!isTypeLegal(VT))
26708     return false;
26709   if (VT != MVT::i16)
26710     return true;
26711
26712   switch (Opc) {
26713   default:
26714     return true;
26715   case ISD::LOAD:
26716   case ISD::SIGN_EXTEND:
26717   case ISD::ZERO_EXTEND:
26718   case ISD::ANY_EXTEND:
26719   case ISD::SHL:
26720   case ISD::SRL:
26721   case ISD::SUB:
26722   case ISD::ADD:
26723   case ISD::MUL:
26724   case ISD::AND:
26725   case ISD::OR:
26726   case ISD::XOR:
26727     return false;
26728   }
26729 }
26730
26731 /// IsDesirableToPromoteOp - This method query the target whether it is
26732 /// beneficial for dag combiner to promote the specified node. If true, it
26733 /// should return the desired promotion type by reference.
26734 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26735   EVT VT = Op.getValueType();
26736   if (VT != MVT::i16)
26737     return false;
26738
26739   bool Promote = false;
26740   bool Commute = false;
26741   switch (Op.getOpcode()) {
26742   default: break;
26743   case ISD::LOAD: {
26744     LoadSDNode *LD = cast<LoadSDNode>(Op);
26745     // If the non-extending load has a single use and it's not live out, then it
26746     // might be folded.
26747     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26748                                                      Op.hasOneUse()*/) {
26749       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26750              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26751         // The only case where we'd want to promote LOAD (rather then it being
26752         // promoted as an operand is when it's only use is liveout.
26753         if (UI->getOpcode() != ISD::CopyToReg)
26754           return false;
26755       }
26756     }
26757     Promote = true;
26758     break;
26759   }
26760   case ISD::SIGN_EXTEND:
26761   case ISD::ZERO_EXTEND:
26762   case ISD::ANY_EXTEND:
26763     Promote = true;
26764     break;
26765   case ISD::SHL:
26766   case ISD::SRL: {
26767     SDValue N0 = Op.getOperand(0);
26768     // Look out for (store (shl (load), x)).
26769     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26770       return false;
26771     Promote = true;
26772     break;
26773   }
26774   case ISD::ADD:
26775   case ISD::MUL:
26776   case ISD::AND:
26777   case ISD::OR:
26778   case ISD::XOR:
26779     Commute = true;
26780     // fallthrough
26781   case ISD::SUB: {
26782     SDValue N0 = Op.getOperand(0);
26783     SDValue N1 = Op.getOperand(1);
26784     if (!Commute && MayFoldLoad(N1))
26785       return false;
26786     // Avoid disabling potential load folding opportunities.
26787     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26788       return false;
26789     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26790       return false;
26791     Promote = true;
26792   }
26793   }
26794
26795   PVT = MVT::i32;
26796   return Promote;
26797 }
26798
26799 //===----------------------------------------------------------------------===//
26800 //                           X86 Inline Assembly Support
26801 //===----------------------------------------------------------------------===//
26802
26803 // Helper to match a string separated by whitespace.
26804 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26805   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26806
26807   for (StringRef Piece : Pieces) {
26808     if (!S.startswith(Piece)) // Check if the piece matches.
26809       return false;
26810
26811     S = S.substr(Piece.size());
26812     StringRef::size_type Pos = S.find_first_not_of(" \t");
26813     if (Pos == 0) // We matched a prefix.
26814       return false;
26815
26816     S = S.substr(Pos);
26817   }
26818
26819   return S.empty();
26820 }
26821
26822 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26823
26824   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26825     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26826         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26827         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26828
26829       if (AsmPieces.size() == 3)
26830         return true;
26831       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26832         return true;
26833     }
26834   }
26835   return false;
26836 }
26837
26838 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26839   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26840
26841   std::string AsmStr = IA->getAsmString();
26842
26843   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26844   if (!Ty || Ty->getBitWidth() % 16 != 0)
26845     return false;
26846
26847   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26848   SmallVector<StringRef, 4> AsmPieces;
26849   SplitString(AsmStr, AsmPieces, ";\n");
26850
26851   switch (AsmPieces.size()) {
26852   default: return false;
26853   case 1:
26854     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26855     // we will turn this bswap into something that will be lowered to logical
26856     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26857     // lower so don't worry about this.
26858     // bswap $0
26859     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26860         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26861         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26862         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26863         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26864         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26865       // No need to check constraints, nothing other than the equivalent of
26866       // "=r,0" would be valid here.
26867       return IntrinsicLowering::LowerToByteSwap(CI);
26868     }
26869
26870     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26871     if (CI->getType()->isIntegerTy(16) &&
26872         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26873         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26874          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26875       AsmPieces.clear();
26876       StringRef ConstraintsStr = IA->getConstraintString();
26877       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26878       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26879       if (clobbersFlagRegisters(AsmPieces))
26880         return IntrinsicLowering::LowerToByteSwap(CI);
26881     }
26882     break;
26883   case 3:
26884     if (CI->getType()->isIntegerTy(32) &&
26885         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26886         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26887         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26888         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26889       AsmPieces.clear();
26890       StringRef ConstraintsStr = IA->getConstraintString();
26891       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26892       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26893       if (clobbersFlagRegisters(AsmPieces))
26894         return IntrinsicLowering::LowerToByteSwap(CI);
26895     }
26896
26897     if (CI->getType()->isIntegerTy(64)) {
26898       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26899       if (Constraints.size() >= 2 &&
26900           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26901           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26902         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26903         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26904             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26905             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26906           return IntrinsicLowering::LowerToByteSwap(CI);
26907       }
26908     }
26909     break;
26910   }
26911   return false;
26912 }
26913
26914 /// getConstraintType - Given a constraint letter, return the type of
26915 /// constraint it is for this target.
26916 X86TargetLowering::ConstraintType
26917 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26918   if (Constraint.size() == 1) {
26919     switch (Constraint[0]) {
26920     case 'R':
26921     case 'q':
26922     case 'Q':
26923     case 'f':
26924     case 't':
26925     case 'u':
26926     case 'y':
26927     case 'x':
26928     case 'Y':
26929     case 'l':
26930       return C_RegisterClass;
26931     case 'a':
26932     case 'b':
26933     case 'c':
26934     case 'd':
26935     case 'S':
26936     case 'D':
26937     case 'A':
26938       return C_Register;
26939     case 'I':
26940     case 'J':
26941     case 'K':
26942     case 'L':
26943     case 'M':
26944     case 'N':
26945     case 'G':
26946     case 'C':
26947     case 'e':
26948     case 'Z':
26949       return C_Other;
26950     default:
26951       break;
26952     }
26953   }
26954   return TargetLowering::getConstraintType(Constraint);
26955 }
26956
26957 /// Examine constraint type and operand type and determine a weight value.
26958 /// This object must already have been set up with the operand type
26959 /// and the current alternative constraint selected.
26960 TargetLowering::ConstraintWeight
26961   X86TargetLowering::getSingleConstraintMatchWeight(
26962     AsmOperandInfo &info, const char *constraint) const {
26963   ConstraintWeight weight = CW_Invalid;
26964   Value *CallOperandVal = info.CallOperandVal;
26965     // If we don't have a value, we can't do a match,
26966     // but allow it at the lowest weight.
26967   if (!CallOperandVal)
26968     return CW_Default;
26969   Type *type = CallOperandVal->getType();
26970   // Look at the constraint type.
26971   switch (*constraint) {
26972   default:
26973     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26974   case 'R':
26975   case 'q':
26976   case 'Q':
26977   case 'a':
26978   case 'b':
26979   case 'c':
26980   case 'd':
26981   case 'S':
26982   case 'D':
26983   case 'A':
26984     if (CallOperandVal->getType()->isIntegerTy())
26985       weight = CW_SpecificReg;
26986     break;
26987   case 'f':
26988   case 't':
26989   case 'u':
26990     if (type->isFloatingPointTy())
26991       weight = CW_SpecificReg;
26992     break;
26993   case 'y':
26994     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26995       weight = CW_SpecificReg;
26996     break;
26997   case 'x':
26998   case 'Y':
26999     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27000         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27001       weight = CW_Register;
27002     break;
27003   case 'I':
27004     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27005       if (C->getZExtValue() <= 31)
27006         weight = CW_Constant;
27007     }
27008     break;
27009   case 'J':
27010     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27011       if (C->getZExtValue() <= 63)
27012         weight = CW_Constant;
27013     }
27014     break;
27015   case 'K':
27016     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27017       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27018         weight = CW_Constant;
27019     }
27020     break;
27021   case 'L':
27022     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27023       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27024         weight = CW_Constant;
27025     }
27026     break;
27027   case 'M':
27028     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27029       if (C->getZExtValue() <= 3)
27030         weight = CW_Constant;
27031     }
27032     break;
27033   case 'N':
27034     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27035       if (C->getZExtValue() <= 0xff)
27036         weight = CW_Constant;
27037     }
27038     break;
27039   case 'G':
27040   case 'C':
27041     if (isa<ConstantFP>(CallOperandVal)) {
27042       weight = CW_Constant;
27043     }
27044     break;
27045   case 'e':
27046     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27047       if ((C->getSExtValue() >= -0x80000000LL) &&
27048           (C->getSExtValue() <= 0x7fffffffLL))
27049         weight = CW_Constant;
27050     }
27051     break;
27052   case 'Z':
27053     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27054       if (C->getZExtValue() <= 0xffffffff)
27055         weight = CW_Constant;
27056     }
27057     break;
27058   }
27059   return weight;
27060 }
27061
27062 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27063 /// with another that has more specific requirements based on the type of the
27064 /// corresponding operand.
27065 const char *X86TargetLowering::
27066 LowerXConstraint(EVT ConstraintVT) const {
27067   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27068   // 'f' like normal targets.
27069   if (ConstraintVT.isFloatingPoint()) {
27070     if (Subtarget->hasSSE2())
27071       return "Y";
27072     if (Subtarget->hasSSE1())
27073       return "x";
27074   }
27075
27076   return TargetLowering::LowerXConstraint(ConstraintVT);
27077 }
27078
27079 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27080 /// vector.  If it is invalid, don't add anything to Ops.
27081 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27082                                                      std::string &Constraint,
27083                                                      std::vector<SDValue>&Ops,
27084                                                      SelectionDAG &DAG) const {
27085   SDValue Result;
27086
27087   // Only support length 1 constraints for now.
27088   if (Constraint.length() > 1) return;
27089
27090   char ConstraintLetter = Constraint[0];
27091   switch (ConstraintLetter) {
27092   default: break;
27093   case 'I':
27094     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27095       if (C->getZExtValue() <= 31) {
27096         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27097                                        Op.getValueType());
27098         break;
27099       }
27100     }
27101     return;
27102   case 'J':
27103     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27104       if (C->getZExtValue() <= 63) {
27105         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27106                                        Op.getValueType());
27107         break;
27108       }
27109     }
27110     return;
27111   case 'K':
27112     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27113       if (isInt<8>(C->getSExtValue())) {
27114         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27115                                        Op.getValueType());
27116         break;
27117       }
27118     }
27119     return;
27120   case 'L':
27121     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27122       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27123           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27124         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27125                                        Op.getValueType());
27126         break;
27127       }
27128     }
27129     return;
27130   case 'M':
27131     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27132       if (C->getZExtValue() <= 3) {
27133         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27134                                        Op.getValueType());
27135         break;
27136       }
27137     }
27138     return;
27139   case 'N':
27140     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27141       if (C->getZExtValue() <= 255) {
27142         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27143                                        Op.getValueType());
27144         break;
27145       }
27146     }
27147     return;
27148   case 'O':
27149     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27150       if (C->getZExtValue() <= 127) {
27151         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27152                                        Op.getValueType());
27153         break;
27154       }
27155     }
27156     return;
27157   case 'e': {
27158     // 32-bit signed value
27159     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27160       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27161                                            C->getSExtValue())) {
27162         // Widen to 64 bits here to get it sign extended.
27163         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27164         break;
27165       }
27166     // FIXME gcc accepts some relocatable values here too, but only in certain
27167     // memory models; it's complicated.
27168     }
27169     return;
27170   }
27171   case 'Z': {
27172     // 32-bit unsigned value
27173     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27174       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27175                                            C->getZExtValue())) {
27176         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27177                                        Op.getValueType());
27178         break;
27179       }
27180     }
27181     // FIXME gcc accepts some relocatable values here too, but only in certain
27182     // memory models; it's complicated.
27183     return;
27184   }
27185   case 'i': {
27186     // Literal immediates are always ok.
27187     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27188       // Widen to 64 bits here to get it sign extended.
27189       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27190       break;
27191     }
27192
27193     // In any sort of PIC mode addresses need to be computed at runtime by
27194     // adding in a register or some sort of table lookup.  These can't
27195     // be used as immediates.
27196     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27197       return;
27198
27199     // If we are in non-pic codegen mode, we allow the address of a global (with
27200     // an optional displacement) to be used with 'i'.
27201     GlobalAddressSDNode *GA = nullptr;
27202     int64_t Offset = 0;
27203
27204     // Match either (GA), (GA+C), (GA+C1+C2), etc.
27205     while (1) {
27206       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27207         Offset += GA->getOffset();
27208         break;
27209       } else if (Op.getOpcode() == ISD::ADD) {
27210         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27211           Offset += C->getZExtValue();
27212           Op = Op.getOperand(0);
27213           continue;
27214         }
27215       } else if (Op.getOpcode() == ISD::SUB) {
27216         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27217           Offset += -C->getZExtValue();
27218           Op = Op.getOperand(0);
27219           continue;
27220         }
27221       }
27222
27223       // Otherwise, this isn't something we can handle, reject it.
27224       return;
27225     }
27226
27227     const GlobalValue *GV = GA->getGlobal();
27228     // If we require an extra load to get this address, as in PIC mode, we
27229     // can't accept it.
27230     if (isGlobalStubReference(
27231             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27232       return;
27233
27234     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27235                                         GA->getValueType(0), Offset);
27236     break;
27237   }
27238   }
27239
27240   if (Result.getNode()) {
27241     Ops.push_back(Result);
27242     return;
27243   }
27244   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27245 }
27246
27247 std::pair<unsigned, const TargetRegisterClass *>
27248 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27249                                                 StringRef Constraint,
27250                                                 MVT VT) const {
27251   // First, see if this is a constraint that directly corresponds to an LLVM
27252   // register class.
27253   if (Constraint.size() == 1) {
27254     // GCC Constraint Letters
27255     switch (Constraint[0]) {
27256     default: break;
27257       // TODO: Slight differences here in allocation order and leaving
27258       // RIP in the class. Do they matter any more here than they do
27259       // in the normal allocation?
27260     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27261       if (Subtarget->is64Bit()) {
27262         if (VT == MVT::i32 || VT == MVT::f32)
27263           return std::make_pair(0U, &X86::GR32RegClass);
27264         if (VT == MVT::i16)
27265           return std::make_pair(0U, &X86::GR16RegClass);
27266         if (VT == MVT::i8 || VT == MVT::i1)
27267           return std::make_pair(0U, &X86::GR8RegClass);
27268         if (VT == MVT::i64 || VT == MVT::f64)
27269           return std::make_pair(0U, &X86::GR64RegClass);
27270         break;
27271       }
27272       // 32-bit fallthrough
27273     case 'Q':   // Q_REGS
27274       if (VT == MVT::i32 || VT == MVT::f32)
27275         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27276       if (VT == MVT::i16)
27277         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27278       if (VT == MVT::i8 || VT == MVT::i1)
27279         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27280       if (VT == MVT::i64)
27281         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27282       break;
27283     case 'r':   // GENERAL_REGS
27284     case 'l':   // INDEX_REGS
27285       if (VT == MVT::i8 || VT == MVT::i1)
27286         return std::make_pair(0U, &X86::GR8RegClass);
27287       if (VT == MVT::i16)
27288         return std::make_pair(0U, &X86::GR16RegClass);
27289       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27290         return std::make_pair(0U, &X86::GR32RegClass);
27291       return std::make_pair(0U, &X86::GR64RegClass);
27292     case 'R':   // LEGACY_REGS
27293       if (VT == MVT::i8 || VT == MVT::i1)
27294         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27295       if (VT == MVT::i16)
27296         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27297       if (VT == MVT::i32 || !Subtarget->is64Bit())
27298         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27299       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27300     case 'f':  // FP Stack registers.
27301       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27302       // value to the correct fpstack register class.
27303       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27304         return std::make_pair(0U, &X86::RFP32RegClass);
27305       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27306         return std::make_pair(0U, &X86::RFP64RegClass);
27307       return std::make_pair(0U, &X86::RFP80RegClass);
27308     case 'y':   // MMX_REGS if MMX allowed.
27309       if (!Subtarget->hasMMX()) break;
27310       return std::make_pair(0U, &X86::VR64RegClass);
27311     case 'Y':   // SSE_REGS if SSE2 allowed
27312       if (!Subtarget->hasSSE2()) break;
27313       // FALL THROUGH.
27314     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27315       if (!Subtarget->hasSSE1()) break;
27316
27317       switch (VT.SimpleTy) {
27318       default: break;
27319       // Scalar SSE types.
27320       case MVT::f32:
27321       case MVT::i32:
27322         return std::make_pair(0U, &X86::FR32RegClass);
27323       case MVT::f64:
27324       case MVT::i64:
27325         return std::make_pair(0U, &X86::FR64RegClass);
27326       // Vector types.
27327       case MVT::v16i8:
27328       case MVT::v8i16:
27329       case MVT::v4i32:
27330       case MVT::v2i64:
27331       case MVT::v4f32:
27332       case MVT::v2f64:
27333         return std::make_pair(0U, &X86::VR128RegClass);
27334       // AVX types.
27335       case MVT::v32i8:
27336       case MVT::v16i16:
27337       case MVT::v8i32:
27338       case MVT::v4i64:
27339       case MVT::v8f32:
27340       case MVT::v4f64:
27341         return std::make_pair(0U, &X86::VR256RegClass);
27342       case MVT::v8f64:
27343       case MVT::v16f32:
27344       case MVT::v16i32:
27345       case MVT::v8i64:
27346         return std::make_pair(0U, &X86::VR512RegClass);
27347       }
27348       break;
27349     }
27350   }
27351
27352   // Use the default implementation in TargetLowering to convert the register
27353   // constraint into a member of a register class.
27354   std::pair<unsigned, const TargetRegisterClass*> Res;
27355   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27356
27357   // Not found as a standard register?
27358   if (!Res.second) {
27359     // Map st(0) -> st(7) -> ST0
27360     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27361         tolower(Constraint[1]) == 's' &&
27362         tolower(Constraint[2]) == 't' &&
27363         Constraint[3] == '(' &&
27364         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27365         Constraint[5] == ')' &&
27366         Constraint[6] == '}') {
27367
27368       Res.first = X86::FP0+Constraint[4]-'0';
27369       Res.second = &X86::RFP80RegClass;
27370       return Res;
27371     }
27372
27373     // GCC allows "st(0)" to be called just plain "st".
27374     if (StringRef("{st}").equals_lower(Constraint)) {
27375       Res.first = X86::FP0;
27376       Res.second = &X86::RFP80RegClass;
27377       return Res;
27378     }
27379
27380     // flags -> EFLAGS
27381     if (StringRef("{flags}").equals_lower(Constraint)) {
27382       Res.first = X86::EFLAGS;
27383       Res.second = &X86::CCRRegClass;
27384       return Res;
27385     }
27386
27387     // 'A' means EAX + EDX.
27388     if (Constraint == "A") {
27389       Res.first = X86::EAX;
27390       Res.second = &X86::GR32_ADRegClass;
27391       return Res;
27392     }
27393     return Res;
27394   }
27395
27396   // Otherwise, check to see if this is a register class of the wrong value
27397   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27398   // turn into {ax},{dx}.
27399   // MVT::Other is used to specify clobber names.
27400   if (Res.second->hasType(VT) || VT == MVT::Other)
27401     return Res;   // Correct type already, nothing to do.
27402
27403   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27404   // return "eax". This should even work for things like getting 64bit integer
27405   // registers when given an f64 type.
27406   const TargetRegisterClass *Class = Res.second;
27407   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27408       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27409     unsigned Size = VT.getSizeInBits();
27410     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27411                                   : Size == 16 ? MVT::i16
27412                                   : Size == 32 ? MVT::i32
27413                                   : Size == 64 ? MVT::i64
27414                                   : MVT::Other;
27415     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27416     if (DestReg > 0) {
27417       Res.first = DestReg;
27418       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27419                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27420                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27421                  : &X86::GR64RegClass;
27422       assert(Res.second->contains(Res.first) && "Register in register class");
27423     } else {
27424       // No register found/type mismatch.
27425       Res.first = 0;
27426       Res.second = nullptr;
27427     }
27428   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27429              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27430              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27431              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27432              Class == &X86::VR512RegClass) {
27433     // Handle references to XMM physical registers that got mapped into the
27434     // wrong class.  This can happen with constraints like {xmm0} where the
27435     // target independent register mapper will just pick the first match it can
27436     // find, ignoring the required type.
27437
27438     if (VT == MVT::f32 || VT == MVT::i32)
27439       Res.second = &X86::FR32RegClass;
27440     else if (VT == MVT::f64 || VT == MVT::i64)
27441       Res.second = &X86::FR64RegClass;
27442     else if (X86::VR128RegClass.hasType(VT))
27443       Res.second = &X86::VR128RegClass;
27444     else if (X86::VR256RegClass.hasType(VT))
27445       Res.second = &X86::VR256RegClass;
27446     else if (X86::VR512RegClass.hasType(VT))
27447       Res.second = &X86::VR512RegClass;
27448     else {
27449       // Type mismatch and not a clobber: Return an error;
27450       Res.first = 0;
27451       Res.second = nullptr;
27452     }
27453   }
27454
27455   return Res;
27456 }
27457
27458 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27459                                             const AddrMode &AM, Type *Ty,
27460                                             unsigned AS) const {
27461   // Scaling factors are not free at all.
27462   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27463   // will take 2 allocations in the out of order engine instead of 1
27464   // for plain addressing mode, i.e. inst (reg1).
27465   // E.g.,
27466   // vaddps (%rsi,%drx), %ymm0, %ymm1
27467   // Requires two allocations (one for the load, one for the computation)
27468   // whereas:
27469   // vaddps (%rsi), %ymm0, %ymm1
27470   // Requires just 1 allocation, i.e., freeing allocations for other operations
27471   // and having less micro operations to execute.
27472   //
27473   // For some X86 architectures, this is even worse because for instance for
27474   // stores, the complex addressing mode forces the instruction to use the
27475   // "load" ports instead of the dedicated "store" port.
27476   // E.g., on Haswell:
27477   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27478   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27479   if (isLegalAddressingMode(DL, AM, Ty, AS))
27480     // Scale represents reg2 * scale, thus account for 1
27481     // as soon as we use a second register.
27482     return AM.Scale != 0;
27483   return -1;
27484 }
27485
27486 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27487   // Integer division on x86 is expensive. However, when aggressively optimizing
27488   // for code size, we prefer to use a div instruction, as it is usually smaller
27489   // than the alternative sequence.
27490   // The exception to this is vector division. Since x86 doesn't have vector
27491   // integer division, leaving the division as-is is a loss even in terms of
27492   // size, because it will have to be scalarized, while the alternative code
27493   // sequence can be performed in vector form.
27494   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27495                                    Attribute::MinSize);
27496   return OptSize && !VT.isVector();
27497 }
27498
27499 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
27500        TargetLowering::ArgListTy& Args) const {
27501   // The MCU psABI requires some arguments to be passed in-register.
27502   // For regular calls, the inreg arguments are marked by the front-end.
27503   // However, for compiler generated library calls, we have to patch this
27504   // up here.
27505   if (!Subtarget->isTargetMCU() || !Args.size())
27506     return;
27507
27508   unsigned FreeRegs = 3;
27509   for (auto &Arg : Args) {
27510     // For library functions, we do not expect any fancy types.
27511     unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
27512     unsigned SizeInRegs = (Size + 31) / 32;
27513     if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
27514       continue;
27515
27516     Arg.isInReg = true;
27517     FreeRegs -= SizeInRegs;
27518     if (!FreeRegs)
27519       break;
27520   }
27521 }