[x86] replace integer 'and' ops with packed SSE FP 'and' ops when operating on FP...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117   }
118
119   if (Subtarget->isTargetDarwin()) {
120     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121     setUseUnderscoreSetJmp(false);
122     setUseUnderscoreLongJmp(false);
123   } else if (Subtarget->isTargetWindowsGNU()) {
124     // MS runtime is weird: it exports _setjmp, but longjmp!
125     setUseUnderscoreSetJmp(true);
126     setUseUnderscoreLongJmp(false);
127   } else {
128     setUseUnderscoreSetJmp(true);
129     setUseUnderscoreLongJmp(true);
130   }
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i8, &X86::GR8RegClass);
134   addRegisterClass(MVT::i16, &X86::GR16RegClass);
135   addRegisterClass(MVT::i32, &X86::GR32RegClass);
136   if (Subtarget->is64Bit())
137     addRegisterClass(MVT::i64, &X86::GR64RegClass);
138
139   for (MVT VT : MVT::integer_valuetypes())
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
141
142   // We don't accept any truncstore of integer registers.
143   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
149
150   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
151
152   // SETOEQ and SETUNE require checking two conditions.
153   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
159
160   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
161   // operation.
162   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
163   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
164   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
165
166   if (Subtarget->is64Bit()) {
167     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168       // f32/f64 are legal, f80 is custom.
169       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
170     else
171       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
172     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
173   } else if (!Subtarget->useSoftFloat()) {
174     // We have an algorithm for SSE2->double, and we turn this into a
175     // 64-bit FILD followed by conditional FADD for other targets.
176     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
177     // We have an algorithm for SSE2, and we turn this into a 64-bit
178     // FILD or VCVTUSI2SS/SD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
180   }
181
182   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
183   // this operation.
184   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
185   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
186
187   if (!Subtarget->useSoftFloat()) {
188     // SSE has no i16 to fp conversion, only i32
189     if (X86ScalarSSEf32) {
190       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
191       // f32 and f64 cases are Legal, f80 case is not
192       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
193     } else {
194       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     }
197   } else {
198     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
199     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
200   }
201
202   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
203   // are Legal, f80 is custom lowered.
204   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
205   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
206
207   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
208   // this operation.
209   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
210   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
211
212   if (X86ScalarSSEf32) {
213     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
214     // f32 and f64 cases are Legal, f80 case is not
215     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
216   } else {
217     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
218     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
219   }
220
221   // Handle FP_TO_UINT by promoting the destination to a larger signed
222   // conversion.
223   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
224   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
225   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
226
227   if (Subtarget->is64Bit()) {
228     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
229       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
230       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
231       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
232     } else {
233       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
234       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
235     }
236   } else if (!Subtarget->useSoftFloat()) {
237     // Since AVX is a superset of SSE3, only check for SSE here.
238     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
239       // Expand FP_TO_UINT into a select.
240       // FIXME: We would like to use a Custom expander here eventually to do
241       // the optimal thing for SSE vs. the default expansion in the legalizer.
242       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
243     else
244       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248
249     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
250   }
251
252   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253   if (!X86ScalarSSEf64) {
254     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
255     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
256     if (Subtarget->is64Bit()) {
257       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
258       // Without SSE, i64->f64 goes through memory.
259       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
260     }
261   }
262
263   // Scalar integer divide and remainder are lowered to use operations that
264   // produce two results, to match the available instructions. This exposes
265   // the two-result form to trivial CSE, which is able to combine x/y and x%y
266   // into a single instruction.
267   //
268   // Scalar integer multiply-high is also lowered to use two-result
269   // operations, to match the available instructions. However, plain multiply
270   // (low) operations are left as Legal, as there are single-result
271   // instructions for this in x86. Using the two-result multiply instructions
272   // when both high and low results are needed must be arranged by dagcombine.
273   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
274     MVT VT = IntVTs[i];
275     setOperationAction(ISD::MULHS, VT, Expand);
276     setOperationAction(ISD::MULHU, VT, Expand);
277     setOperationAction(ISD::SDIV, VT, Expand);
278     setOperationAction(ISD::UDIV, VT, Expand);
279     setOperationAction(ISD::SREM, VT, Expand);
280     setOperationAction(ISD::UREM, VT, Expand);
281
282     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283     setOperationAction(ISD::ADDC, VT, Custom);
284     setOperationAction(ISD::ADDE, VT, Custom);
285     setOperationAction(ISD::SUBC, VT, Custom);
286     setOperationAction(ISD::SUBE, VT, Custom);
287   }
288
289   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
290   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
291   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
305   if (Subtarget->is64Bit())
306     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
308   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
309   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
310   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
311
312   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
313     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
314     // is. We should promote the value to 64-bits to solve this.
315     // This is what the CRT headers do - `fmodf` is an inline header
316     // function casting to f64 and calling `fmod`.
317     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
318   } else {
319     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
320   }
321
322   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
323   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
324   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
325
326   // Promote the i8 variants and force them on up to i32 which has a shorter
327   // encoding.
328   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
329   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
330   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
331   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
332   if (Subtarget->hasBMI()) {
333     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
334     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
335     if (Subtarget->is64Bit())
336       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
337   } else {
338     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
339     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
342   }
343
344   if (Subtarget->hasLZCNT()) {
345     // When promoting the i8 variants, force them to i32 for a shorter
346     // encoding.
347     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
348     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
350     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
352     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
353     if (Subtarget->is64Bit())
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
355   } else {
356     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
357     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
358     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
359     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
360     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
361     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
364       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
365     }
366   }
367
368   // Special handling for half-precision floating point conversions.
369   // If we don't have F16C support, then lower half float conversions
370   // into library calls.
371   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
374   }
375
376   // There's never any support for operations beyond MVT::f32.
377   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
381
382   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400
401   if (!Subtarget->hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403
404   // These should be promoted to a larger select which is supported.
405   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
406   // X86 wants to expand cmov itself.
407   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
408   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
411   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
412   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
414   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
417   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
421     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
422   }
423   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
424   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426   // support continuation, user-level threading, and etc.. As a result, no
427   // other SjLj exception interfaces are implemented and please don't build
428   // your own exception handling based on them.
429   // LLVM/Clang supports zero-cost DWARF exception handling.
430   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
432
433   // Darwin ABI issue.
434   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
435   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
436   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
437   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
438   if (Subtarget->is64Bit())
439     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
441   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
442   if (Subtarget->is64Bit()) {
443     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
444     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
445     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
446     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
447     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
448   }
449   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
451   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
452   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
455     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
456     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
457   }
458
459   if (Subtarget->hasSSE1())
460     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
461
462   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
463
464   // Expand certain atomics
465   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
466     MVT VT = IntVTs[i];
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
470   }
471
472   if (Subtarget->hasCmpxchg16b()) {
473     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
474   }
475
476   // FIXME - use subtarget debug flags
477   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481
482   if (Subtarget->isTarget64BitLP64()) {
483     setExceptionPointerRegister(X86::RAX);
484     setExceptionSelectorRegister(X86::RDX);
485   } else {
486     setExceptionPointerRegister(X86::EAX);
487     setExceptionSelectorRegister(X86::EDX);
488   }
489   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
491
492   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
494
495   setOperationAction(ISD::TRAP, MVT::Other, Legal);
496   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
497
498   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
500   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
501   if (Subtarget->is64Bit()) {
502     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
503     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
504   } else {
505     // TargetInfo::CharPtrBuiltinVaList
506     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
507     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
508   }
509
510   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
511   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
512
513   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
514
515   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
517   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
518
519   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
520     // f32 and f64 use SSE.
521     // Set up the FP register classes.
522     addRegisterClass(MVT::f32, &X86::FR32RegClass);
523     addRegisterClass(MVT::f64, &X86::FR64RegClass);
524
525     // Use ANDPD to simulate FABS.
526     setOperationAction(ISD::FABS , MVT::f64, Custom);
527     setOperationAction(ISD::FABS , MVT::f32, Custom);
528
529     // Use XORP to simulate FNEG.
530     setOperationAction(ISD::FNEG , MVT::f64, Custom);
531     setOperationAction(ISD::FNEG , MVT::f32, Custom);
532
533     // Use ANDPD and ORPD to simulate FCOPYSIGN.
534     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
535     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
536
537     // Lower this to FGETSIGNx86 plus an AND.
538     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
539     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
540
541     // We don't support sin/cos/fmod
542     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
543     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
544     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
545     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
546     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
547     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
548
549     // Expand FP immediates into loads from the stack, except for the special
550     // cases we handle.
551     addLegalFPImmediate(APFloat(+0.0)); // xorpd
552     addLegalFPImmediate(APFloat(+0.0f)); // xorps
553   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
554     // Use SSE for f32, x87 for f64.
555     // Set up the FP register classes.
556     addRegisterClass(MVT::f32, &X86::FR32RegClass);
557     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
558
559     // Use ANDPS to simulate FABS.
560     setOperationAction(ISD::FABS , MVT::f32, Custom);
561
562     // Use XORP to simulate FNEG.
563     setOperationAction(ISD::FNEG , MVT::f32, Custom);
564
565     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
566
567     // Use ANDPS and ORPS to simulate FCOPYSIGN.
568     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
569     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
570
571     // We don't support sin/cos/fmod
572     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
573     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
574     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
575
576     // Special cases we handle for FP constants.
577     addLegalFPImmediate(APFloat(+0.0f)); // xorps
578     addLegalFPImmediate(APFloat(+0.0)); // FLD0
579     addLegalFPImmediate(APFloat(+1.0)); // FLD1
580     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
581     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
582
583     if (!TM.Options.UnsafeFPMath) {
584       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
585       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
586       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
587     }
588   } else if (!Subtarget->useSoftFloat()) {
589     // f32 and f64 in x87.
590     // Set up the FP register classes.
591     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
592     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
593
594     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
595     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
596     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
598
599     if (!TM.Options.UnsafeFPMath) {
600       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
601       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
602       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
604       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
606     }
607     addLegalFPImmediate(APFloat(+0.0)); // FLD0
608     addLegalFPImmediate(APFloat(+1.0)); // FLD1
609     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
615   }
616
617   // We don't support FMA.
618   setOperationAction(ISD::FMA, MVT::f64, Expand);
619   setOperationAction(ISD::FMA, MVT::f32, Expand);
620
621   // Long double always uses X87.
622   if (!Subtarget->useSoftFloat()) {
623     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
624     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
626     {
627       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
628       addLegalFPImmediate(TmpFlt);  // FLD0
629       TmpFlt.changeSign();
630       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
631
632       bool ignored;
633       APFloat TmpFlt2(+1.0);
634       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
635                       &ignored);
636       addLegalFPImmediate(TmpFlt2);  // FLD1
637       TmpFlt2.changeSign();
638       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
639     }
640
641     if (!TM.Options.UnsafeFPMath) {
642       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
643       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
644       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
645     }
646
647     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
648     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
649     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
650     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
651     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
652     setOperationAction(ISD::FMA, MVT::f80, Expand);
653   }
654
655   // Always use a library call for pow.
656   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
657   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
659
660   setOperationAction(ISD::FLOG, MVT::f80, Expand);
661   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
663   setOperationAction(ISD::FEXP, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
665   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
666   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
667
668   // First set operation action for all vector types to either promote
669   // (for widening) or expand (for scalarization). Then we will selectively
670   // turn on ones that can be effectively codegen'd.
671   for (MVT VT : MVT::vector_valuetypes()) {
672     setOperationAction(ISD::ADD , VT, Expand);
673     setOperationAction(ISD::SUB , VT, Expand);
674     setOperationAction(ISD::FADD, VT, Expand);
675     setOperationAction(ISD::FNEG, VT, Expand);
676     setOperationAction(ISD::FSUB, VT, Expand);
677     setOperationAction(ISD::MUL , VT, Expand);
678     setOperationAction(ISD::FMUL, VT, Expand);
679     setOperationAction(ISD::SDIV, VT, Expand);
680     setOperationAction(ISD::UDIV, VT, Expand);
681     setOperationAction(ISD::FDIV, VT, Expand);
682     setOperationAction(ISD::SREM, VT, Expand);
683     setOperationAction(ISD::UREM, VT, Expand);
684     setOperationAction(ISD::LOAD, VT, Expand);
685     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
686     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
687     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
688     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
689     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::FABS, VT, Expand);
691     setOperationAction(ISD::FSIN, VT, Expand);
692     setOperationAction(ISD::FSINCOS, VT, Expand);
693     setOperationAction(ISD::FCOS, VT, Expand);
694     setOperationAction(ISD::FSINCOS, VT, Expand);
695     setOperationAction(ISD::FREM, VT, Expand);
696     setOperationAction(ISD::FMA,  VT, Expand);
697     setOperationAction(ISD::FPOWI, VT, Expand);
698     setOperationAction(ISD::FSQRT, VT, Expand);
699     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
700     setOperationAction(ISD::FFLOOR, VT, Expand);
701     setOperationAction(ISD::FCEIL, VT, Expand);
702     setOperationAction(ISD::FTRUNC, VT, Expand);
703     setOperationAction(ISD::FRINT, VT, Expand);
704     setOperationAction(ISD::FNEARBYINT, VT, Expand);
705     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
706     setOperationAction(ISD::MULHS, VT, Expand);
707     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
708     setOperationAction(ISD::MULHU, VT, Expand);
709     setOperationAction(ISD::SDIVREM, VT, Expand);
710     setOperationAction(ISD::UDIVREM, VT, Expand);
711     setOperationAction(ISD::FPOW, VT, Expand);
712     setOperationAction(ISD::CTPOP, VT, Expand);
713     setOperationAction(ISD::CTTZ, VT, Expand);
714     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
715     setOperationAction(ISD::CTLZ, VT, Expand);
716     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
717     setOperationAction(ISD::SHL, VT, Expand);
718     setOperationAction(ISD::SRA, VT, Expand);
719     setOperationAction(ISD::SRL, VT, Expand);
720     setOperationAction(ISD::ROTL, VT, Expand);
721     setOperationAction(ISD::ROTR, VT, Expand);
722     setOperationAction(ISD::BSWAP, VT, Expand);
723     setOperationAction(ISD::SETCC, VT, Expand);
724     setOperationAction(ISD::FLOG, VT, Expand);
725     setOperationAction(ISD::FLOG2, VT, Expand);
726     setOperationAction(ISD::FLOG10, VT, Expand);
727     setOperationAction(ISD::FEXP, VT, Expand);
728     setOperationAction(ISD::FEXP2, VT, Expand);
729     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
730     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
731     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
732     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
734     setOperationAction(ISD::TRUNCATE, VT, Expand);
735     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
736     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
737     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
738     setOperationAction(ISD::VSELECT, VT, Expand);
739     setOperationAction(ISD::SELECT_CC, VT, Expand);
740     for (MVT InnerVT : MVT::vector_valuetypes()) {
741       setTruncStoreAction(InnerVT, VT, Expand);
742
743       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
744       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
745
746       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
747       // types, we have to deal with them whether we ask for Expansion or not.
748       // Setting Expand causes its own optimisation problems though, so leave
749       // them legal.
750       if (VT.getVectorElementType() == MVT::i1)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752
753       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
754       // split/scalarized right now.
755       if (VT.getVectorElementType() == MVT::f16)
756         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
757     }
758   }
759
760   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
761   // with -msoft-float, disable use of MMX as well.
762   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
763     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
764     // No operations on x86mmx supported, everything uses intrinsics.
765   }
766
767   // MMX-sized vectors (other than x86mmx) are expected to be expanded
768   // into smaller operations.
769   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
770     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
771     setOperationAction(ISD::AND,                MMXTy,      Expand);
772     setOperationAction(ISD::OR,                 MMXTy,      Expand);
773     setOperationAction(ISD::XOR,                MMXTy,      Expand);
774     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
775     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
776     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
777   }
778   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
779
780   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
781     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
782
783     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
784     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
788     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
789     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
790     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
791     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
792     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
793     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
794     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
795     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
796     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
797   }
798
799   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
800     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
801
802     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
803     // registers cannot be used even for integer operations.
804     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
805     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
806     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
807     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
808
809     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
810     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
811     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
812     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
813     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
814     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
815     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
816     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
817     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
819     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
820     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
821     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
822     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
823     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
825     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
830     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
831     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
834     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
835     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
836     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
837
838     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
839     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
840     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
841     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
842
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
844     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
848
849     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
850     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
851     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
852     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
853
854     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
855     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
856     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
857     // ISD::CTTZ v2i64 - scalarization is faster.
858     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
861     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
862
863     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
864     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
865       MVT VT = (MVT::SimpleValueType)i;
866       // Do not attempt to custom lower non-power-of-2 vectors
867       if (!isPowerOf2_32(VT.getVectorNumElements()))
868         continue;
869       // Do not attempt to custom lower non-128-bit vectors
870       if (!VT.is128BitVector())
871         continue;
872       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
873       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
874       setOperationAction(ISD::VSELECT,            VT, Custom);
875       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
876     }
877
878     // We support custom legalizing of sext and anyext loads for specific
879     // memory vector types which we can load as a scalar (or sequence of
880     // scalars) and extend in-register to a legal 128-bit vector type. For sext
881     // loads these must work with a single scalar load.
882     for (MVT VT : MVT::integer_vector_valuetypes()) {
883       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
884       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
885       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
886       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
887       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
888       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
889       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
890       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
891       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
892     }
893
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
895     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
897     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
898     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
899     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
900     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
901     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
902
903     if (Subtarget->is64Bit()) {
904       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
906     }
907
908     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910       MVT VT = (MVT::SimpleValueType)i;
911
912       // Do not attempt to promote non-128-bit vectors
913       if (!VT.is128BitVector())
914         continue;
915
916       setOperationAction(ISD::AND,    VT, Promote);
917       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
918       setOperationAction(ISD::OR,     VT, Promote);
919       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
920       setOperationAction(ISD::XOR,    VT, Promote);
921       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
922       setOperationAction(ISD::LOAD,   VT, Promote);
923       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
924       setOperationAction(ISD::SELECT, VT, Promote);
925       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
926     }
927
928     // Custom lower v2i64 and v2f64 selects.
929     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
930     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
931     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
932     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
933
934     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
935     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
936
937     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
938
939     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
940     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
941     // As there is no 64-bit GPR available, we need build a special custom
942     // sequence to convert from v2i32 to v2f32.
943     if (!Subtarget->is64Bit())
944       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
945
946     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
947     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
948
949     for (MVT VT : MVT::fp_vector_valuetypes())
950       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
951
952     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
953     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
954     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
955   }
956
957   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
960       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
961       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
962       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
963       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
964     }
965
966     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
967     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
968     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
969     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
970     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
971     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
972     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
973     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
974
975     // FIXME: Do we need to handle scalar-to-vector here?
976     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
977
978     // We directly match byte blends in the backend as they match the VSELECT
979     // condition form.
980     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
981
982     // SSE41 brings specific instructions for doing vector sign extend even in
983     // cases where we don't have SRA.
984     for (MVT VT : MVT::integer_vector_valuetypes()) {
985       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
988     }
989
990     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
992     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
993     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
994     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
997
998     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
999     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
1000     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
1001     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1004
1005     // i8 and i16 vectors are custom because the source register and source
1006     // source memory operand types are not the same width.  f32 vectors are
1007     // custom since the immediate controlling the insert encodes additional
1008     // information.
1009     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1010     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1011     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1012     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1013
1014     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1018
1019     // FIXME: these should be Legal, but that's only for the case where
1020     // the index is constant.  For now custom expand to deal with that.
1021     if (Subtarget->is64Bit()) {
1022       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1023       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1024     }
1025   }
1026
1027   if (Subtarget->hasSSE2()) {
1028     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1031
1032     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1033     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1034
1035     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1036     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1037
1038     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1039     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1040
1041     // In the customized shift lowering, the legal cases in AVX2 will be
1042     // recognized.
1043     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1044     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1045
1046     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1047     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1048
1049     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1050     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1051   }
1052
1053   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1054     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1055     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1056     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1057     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1059     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1060
1061     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1062     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1063     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1064
1065     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1066     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1069     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1070     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1071     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1072     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1073     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1074     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1075     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1076     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1077
1078     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1079     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1082     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1083     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1084     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1085     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1086     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1087     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1088     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1089     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1090
1091     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1092     // even though v8i16 is a legal type.
1093     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1094     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1095     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1096
1097     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1098     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1099     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1100
1101     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1102     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1103
1104     for (MVT VT : MVT::fp_vector_valuetypes())
1105       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1106
1107     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1114     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1115
1116     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1117     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1118     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1119     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1120
1121     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1122     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1123     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1124
1125     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1126     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1127     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1128     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1129     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1130     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1131     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1132     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1133     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1134     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1135     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1136     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1137
1138     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1139     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1140     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1141     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1142
1143     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1144     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1145     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1146     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1147     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1148     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1149     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1150     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1151
1152     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1153       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1154       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1155       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1156       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1157       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1158       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1159     }
1160
1161     if (Subtarget->hasInt256()) {
1162       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1163       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1164       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1165       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1166
1167       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1168       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1169       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1170       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1171
1172       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1173       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1174       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1175       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1176
1177       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1178       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1179       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1180       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1181
1182       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1183       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1184       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1185       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1186       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1187       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1188       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1189       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1190       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1191       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1192       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1193       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1194
1195       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1196       // when we have a 256bit-wide blend with immediate.
1197       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1198
1199       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1201       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1202       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1203       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1204       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1205       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1206
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1208       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1209       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1210       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1211       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1212       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1213     } else {
1214       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1215       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1216       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1217       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1218
1219       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1220       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1221       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1222       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1223
1224       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1227       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1228
1229       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1230       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1231       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1232       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1233       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1234       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1235       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1236       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1237       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1238       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1239       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1240       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1241     }
1242
1243     // In the customized shift lowering, the legal cases in AVX2 will be
1244     // recognized.
1245     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1246     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1247
1248     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1249     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1250
1251     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1253
1254     // Custom lower several nodes for 256-bit types.
1255     for (MVT VT : MVT::vector_valuetypes()) {
1256       if (VT.getScalarSizeInBits() >= 32) {
1257         setOperationAction(ISD::MLOAD,  VT, Legal);
1258         setOperationAction(ISD::MSTORE, VT, Legal);
1259       }
1260       // Extract subvector is special because the value type
1261       // (result) is 128-bit but the source is 256-bit wide.
1262       if (VT.is128BitVector()) {
1263         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1264       }
1265       // Do not attempt to custom lower other non-256-bit vectors
1266       if (!VT.is256BitVector())
1267         continue;
1268
1269       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1270       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1271       setOperationAction(ISD::VSELECT,            VT, Custom);
1272       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1273       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1275       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1276       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1277     }
1278
1279     if (Subtarget->hasInt256())
1280       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1281
1282     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284       MVT VT = (MVT::SimpleValueType)i;
1285
1286       // Do not attempt to promote non-256-bit vectors
1287       if (!VT.is256BitVector())
1288         continue;
1289
1290       setOperationAction(ISD::AND,    VT, Promote);
1291       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1292       setOperationAction(ISD::OR,     VT, Promote);
1293       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1294       setOperationAction(ISD::XOR,    VT, Promote);
1295       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1296       setOperationAction(ISD::LOAD,   VT, Promote);
1297       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1298       setOperationAction(ISD::SELECT, VT, Promote);
1299       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1300     }
1301   }
1302
1303   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1304     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1307     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1308
1309     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1310     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1311     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1312
1313     for (MVT VT : MVT::fp_vector_valuetypes())
1314       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1315
1316     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1317     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1318     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1319     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1320     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1321     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1322     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1323     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1324     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1325     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1326     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1327     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1328
1329     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1330     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1331     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1332     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1333     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1334     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1335     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1336     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1337     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1340     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1341     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1342
1343     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1344     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1348     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1349
1350     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1356     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1357     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1358
1359     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1362     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1363     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1365     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1366     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1367     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1368     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1370     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1371     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1372     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1373     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1374     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1375
1376     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1377     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1378     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1379     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1380     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1381     if (Subtarget->hasVLX()){
1382       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1383       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1384       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1385       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1386       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1387
1388       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1389       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1390       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1391       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1392       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1393     }
1394     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1395     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1396     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1397     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1398     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1399     if (Subtarget->hasDQI()) {
1400       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1401       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1402
1403       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1404       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1405       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1406       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1407       if (Subtarget->hasVLX()) {
1408         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1409         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1410         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1411         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1412         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1413         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1414         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1415         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1416       }
1417     }
1418     if (Subtarget->hasVLX()) {
1419       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1420       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1421       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1422       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1423       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1424       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1425       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1426       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1427     }
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1434     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1438     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1439     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1440     if (Subtarget->hasDQI()) {
1441       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1442       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1443     }
1444     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1445     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1446     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1447     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1448     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1449     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1450     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1451     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1452     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1453     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1454
1455     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1456     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1457     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1458     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1459     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1460
1461     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1462     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1463
1464     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1465
1466     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1467     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1468     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1469     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1470     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1471     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1472     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1473     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1474     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1475     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1476     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1477
1478     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1479     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1480     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1481     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1482     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1483     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1484     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1485     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1486
1487     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1488     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1489
1490     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1491     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1492
1493     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1494
1495     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1496     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1497
1498     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1499     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1500
1501     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1502     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1503
1504     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1505     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1506     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1507     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1508     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1509     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1510
1511     if (Subtarget->hasCDI()) {
1512       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1513       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1514       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64, Legal);
1515       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1516
1517       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64, Custom);
1518       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1519     }
1520     if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1521       setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1522       setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1523       setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1524       setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1525       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1526       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1527       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1528       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1529
1530       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1531       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1532       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1533       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1534     }
1535     if (Subtarget->hasDQI()) {
1536       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1537       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1538       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1539     }
1540     // Custom lower several nodes.
1541     for (MVT VT : MVT::vector_valuetypes()) {
1542       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1543       if (EltSize == 1) {
1544         setOperationAction(ISD::AND, VT, Legal);
1545         setOperationAction(ISD::OR,  VT, Legal);
1546         setOperationAction(ISD::XOR,  VT, Legal);
1547       }
1548       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1549         setOperationAction(ISD::MGATHER,  VT, Custom);
1550         setOperationAction(ISD::MSCATTER, VT, Custom);
1551       }
1552       // Extract subvector is special because the value type
1553       // (result) is 256/128-bit but the source is 512-bit wide.
1554       if (VT.is128BitVector() || VT.is256BitVector()) {
1555         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1556       }
1557       if (VT.getVectorElementType() == MVT::i1)
1558         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1559
1560       // Do not attempt to custom lower other non-512-bit vectors
1561       if (!VT.is512BitVector())
1562         continue;
1563
1564       if (EltSize >= 32) {
1565         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1566         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1567         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1568         setOperationAction(ISD::VSELECT,             VT, Legal);
1569         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1570         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1571         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1572         setOperationAction(ISD::MLOAD,               VT, Legal);
1573         setOperationAction(ISD::MSTORE,              VT, Legal);
1574       }
1575     }
1576     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1577       MVT VT = (MVT::SimpleValueType)i;
1578
1579       // Do not attempt to promote non-512-bit vectors.
1580       if (!VT.is512BitVector())
1581         continue;
1582
1583       setOperationAction(ISD::SELECT, VT, Promote);
1584       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1585     }
1586   }// has  AVX-512
1587
1588   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1589     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1590     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1591
1592     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1593     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1594
1595     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1596     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1597     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1598     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1599     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1600     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1601     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1602     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1603     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1604     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1605     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1606     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Legal);
1607     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Legal);
1608     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1609     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1610     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1611     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1612     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1613     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1614     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1615     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1616     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1617     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1618     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1619     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1620     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1621     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1622     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1623     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1624     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1625     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1626     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1627     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1628
1629     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1630     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1631     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1632     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1633     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1634     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1635     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1636     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1637
1638     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1639     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1640     if (Subtarget->hasVLX())
1641       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1642
1643     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1644       const MVT VT = (MVT::SimpleValueType)i;
1645
1646       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1647
1648       // Do not attempt to promote non-512-bit vectors.
1649       if (!VT.is512BitVector())
1650         continue;
1651
1652       if (EltSize < 32) {
1653         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1654         setOperationAction(ISD::VSELECT,             VT, Legal);
1655       }
1656     }
1657   }
1658
1659   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1660     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1661     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1662
1663     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1664     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1665     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1666     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1667     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1668     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1669     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1670     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1671     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1672     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1673     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1674     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1675
1676     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1677     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1678     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1679     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1680     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1681     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1682     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1683     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1684
1685     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1686     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1687     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1688     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1689     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1690     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1691     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1692     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1693   }
1694
1695   // We want to custom lower some of our intrinsics.
1696   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1697   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1698   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1699   if (!Subtarget->is64Bit())
1700     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1701
1702   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1703   // handle type legalization for these operations here.
1704   //
1705   // FIXME: We really should do custom legalization for addition and
1706   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1707   // than generic legalization for 64-bit multiplication-with-overflow, though.
1708   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1709     // Add/Sub/Mul with overflow operations are custom lowered.
1710     MVT VT = IntVTs[i];
1711     setOperationAction(ISD::SADDO, VT, Custom);
1712     setOperationAction(ISD::UADDO, VT, Custom);
1713     setOperationAction(ISD::SSUBO, VT, Custom);
1714     setOperationAction(ISD::USUBO, VT, Custom);
1715     setOperationAction(ISD::SMULO, VT, Custom);
1716     setOperationAction(ISD::UMULO, VT, Custom);
1717   }
1718
1719   if (!Subtarget->is64Bit()) {
1720     // These libcalls are not available in 32-bit.
1721     setLibcallName(RTLIB::SHL_I128, nullptr);
1722     setLibcallName(RTLIB::SRL_I128, nullptr);
1723     setLibcallName(RTLIB::SRA_I128, nullptr);
1724   }
1725
1726   // Combine sin / cos into one node or libcall if possible.
1727   if (Subtarget->hasSinCos()) {
1728     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1729     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1730     if (Subtarget->isTargetDarwin()) {
1731       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1732       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1733       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1734       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1735     }
1736   }
1737
1738   if (Subtarget->isTargetWin64()) {
1739     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1740     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1741     setOperationAction(ISD::SREM, MVT::i128, Custom);
1742     setOperationAction(ISD::UREM, MVT::i128, Custom);
1743     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1744     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1745   }
1746
1747   // We have target-specific dag combine patterns for the following nodes:
1748   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1749   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1750   setTargetDAGCombine(ISD::BITCAST);
1751   setTargetDAGCombine(ISD::VSELECT);
1752   setTargetDAGCombine(ISD::SELECT);
1753   setTargetDAGCombine(ISD::SHL);
1754   setTargetDAGCombine(ISD::SRA);
1755   setTargetDAGCombine(ISD::SRL);
1756   setTargetDAGCombine(ISD::OR);
1757   setTargetDAGCombine(ISD::AND);
1758   setTargetDAGCombine(ISD::ADD);
1759   setTargetDAGCombine(ISD::FADD);
1760   setTargetDAGCombine(ISD::FSUB);
1761   setTargetDAGCombine(ISD::FMA);
1762   setTargetDAGCombine(ISD::SUB);
1763   setTargetDAGCombine(ISD::LOAD);
1764   setTargetDAGCombine(ISD::MLOAD);
1765   setTargetDAGCombine(ISD::STORE);
1766   setTargetDAGCombine(ISD::MSTORE);
1767   setTargetDAGCombine(ISD::ZERO_EXTEND);
1768   setTargetDAGCombine(ISD::ANY_EXTEND);
1769   setTargetDAGCombine(ISD::SIGN_EXTEND);
1770   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1771   setTargetDAGCombine(ISD::SINT_TO_FP);
1772   setTargetDAGCombine(ISD::UINT_TO_FP);
1773   setTargetDAGCombine(ISD::SETCC);
1774   setTargetDAGCombine(ISD::BUILD_VECTOR);
1775   setTargetDAGCombine(ISD::MUL);
1776   setTargetDAGCombine(ISD::XOR);
1777
1778   computeRegisterProperties(Subtarget->getRegisterInfo());
1779
1780   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1781   MaxStoresPerMemsetOptSize = 8;
1782   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1783   MaxStoresPerMemcpyOptSize = 4;
1784   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1785   MaxStoresPerMemmoveOptSize = 4;
1786   setPrefLoopAlignment(4); // 2^4 bytes.
1787
1788   // Predictable cmov don't hurt on atom because it's in-order.
1789   PredictableSelectIsExpensive = !Subtarget->isAtom();
1790   EnableExtLdPromotion = true;
1791   setPrefFunctionAlignment(4); // 2^4 bytes.
1792
1793   verifyIntrinsicTables();
1794 }
1795
1796 // This has so far only been implemented for 64-bit MachO.
1797 bool X86TargetLowering::useLoadStackGuardNode() const {
1798   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1799 }
1800
1801 TargetLoweringBase::LegalizeTypeAction
1802 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1803   if (ExperimentalVectorWideningLegalization &&
1804       VT.getVectorNumElements() != 1 &&
1805       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1806     return TypeWidenVector;
1807
1808   return TargetLoweringBase::getPreferredVectorAction(VT);
1809 }
1810
1811 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1812                                           EVT VT) const {
1813   if (!VT.isVector())
1814     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1815
1816   const unsigned NumElts = VT.getVectorNumElements();
1817   const EVT EltVT = VT.getVectorElementType();
1818   if (VT.is512BitVector()) {
1819     if (Subtarget->hasAVX512())
1820       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1821           EltVT == MVT::f32 || EltVT == MVT::f64)
1822         switch(NumElts) {
1823         case  8: return MVT::v8i1;
1824         case 16: return MVT::v16i1;
1825       }
1826     if (Subtarget->hasBWI())
1827       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1828         switch(NumElts) {
1829         case 32: return MVT::v32i1;
1830         case 64: return MVT::v64i1;
1831       }
1832   }
1833
1834   if (VT.is256BitVector() || VT.is128BitVector()) {
1835     if (Subtarget->hasVLX())
1836       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1837           EltVT == MVT::f32 || EltVT == MVT::f64)
1838         switch(NumElts) {
1839         case 2: return MVT::v2i1;
1840         case 4: return MVT::v4i1;
1841         case 8: return MVT::v8i1;
1842       }
1843     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1844       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1845         switch(NumElts) {
1846         case  8: return MVT::v8i1;
1847         case 16: return MVT::v16i1;
1848         case 32: return MVT::v32i1;
1849       }
1850   }
1851
1852   return VT.changeVectorElementTypeToInteger();
1853 }
1854
1855 /// Helper for getByValTypeAlignment to determine
1856 /// the desired ByVal argument alignment.
1857 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1858   if (MaxAlign == 16)
1859     return;
1860   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1861     if (VTy->getBitWidth() == 128)
1862       MaxAlign = 16;
1863   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1864     unsigned EltAlign = 0;
1865     getMaxByValAlign(ATy->getElementType(), EltAlign);
1866     if (EltAlign > MaxAlign)
1867       MaxAlign = EltAlign;
1868   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1869     for (auto *EltTy : STy->elements()) {
1870       unsigned EltAlign = 0;
1871       getMaxByValAlign(EltTy, EltAlign);
1872       if (EltAlign > MaxAlign)
1873         MaxAlign = EltAlign;
1874       if (MaxAlign == 16)
1875         break;
1876     }
1877   }
1878 }
1879
1880 /// Return the desired alignment for ByVal aggregate
1881 /// function arguments in the caller parameter area. For X86, aggregates
1882 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1883 /// are at 4-byte boundaries.
1884 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1885                                                   const DataLayout &DL) const {
1886   if (Subtarget->is64Bit()) {
1887     // Max of 8 and alignment of type.
1888     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1889     if (TyAlign > 8)
1890       return TyAlign;
1891     return 8;
1892   }
1893
1894   unsigned Align = 4;
1895   if (Subtarget->hasSSE1())
1896     getMaxByValAlign(Ty, Align);
1897   return Align;
1898 }
1899
1900 /// Returns the target specific optimal type for load
1901 /// and store operations as a result of memset, memcpy, and memmove
1902 /// lowering. If DstAlign is zero that means it's safe to destination
1903 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1904 /// means there isn't a need to check it against alignment requirement,
1905 /// probably because the source does not need to be loaded. If 'IsMemset' is
1906 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1907 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1908 /// source is constant so it does not need to be loaded.
1909 /// It returns EVT::Other if the type should be determined using generic
1910 /// target-independent logic.
1911 EVT
1912 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1913                                        unsigned DstAlign, unsigned SrcAlign,
1914                                        bool IsMemset, bool ZeroMemset,
1915                                        bool MemcpyStrSrc,
1916                                        MachineFunction &MF) const {
1917   const Function *F = MF.getFunction();
1918   if ((!IsMemset || ZeroMemset) &&
1919       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1920     if (Size >= 16 &&
1921         (!Subtarget->isUnalignedMem16Slow() ||
1922          ((DstAlign == 0 || DstAlign >= 16) &&
1923           (SrcAlign == 0 || SrcAlign >= 16)))) {
1924       if (Size >= 32) {
1925         // FIXME: Check if unaligned 32-byte accesses are slow.
1926         if (Subtarget->hasInt256())
1927           return MVT::v8i32;
1928         if (Subtarget->hasFp256())
1929           return MVT::v8f32;
1930       }
1931       if (Subtarget->hasSSE2())
1932         return MVT::v4i32;
1933       if (Subtarget->hasSSE1())
1934         return MVT::v4f32;
1935     } else if (!MemcpyStrSrc && Size >= 8 &&
1936                !Subtarget->is64Bit() &&
1937                Subtarget->hasSSE2()) {
1938       // Do not use f64 to lower memcpy if source is string constant. It's
1939       // better to use i32 to avoid the loads.
1940       return MVT::f64;
1941     }
1942   }
1943   // This is a compromise. If we reach here, unaligned accesses may be slow on
1944   // this target. However, creating smaller, aligned accesses could be even
1945   // slower and would certainly be a lot more code.
1946   if (Subtarget->is64Bit() && Size >= 8)
1947     return MVT::i64;
1948   return MVT::i32;
1949 }
1950
1951 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1952   if (VT == MVT::f32)
1953     return X86ScalarSSEf32;
1954   else if (VT == MVT::f64)
1955     return X86ScalarSSEf64;
1956   return true;
1957 }
1958
1959 bool
1960 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1961                                                   unsigned,
1962                                                   unsigned,
1963                                                   bool *Fast) const {
1964   if (Fast) {
1965     switch (VT.getSizeInBits()) {
1966     default:
1967       // 8-byte and under are always assumed to be fast.
1968       *Fast = true;
1969       break;
1970     case 128:
1971       *Fast = !Subtarget->isUnalignedMem16Slow();
1972       break;
1973     case 256:
1974       *Fast = !Subtarget->isUnalignedMem32Slow();
1975       break;
1976     // TODO: What about AVX-512 (512-bit) accesses?
1977     }
1978   }
1979   // Misaligned accesses of any size are always allowed.
1980   return true;
1981 }
1982
1983 /// Return the entry encoding for a jump table in the
1984 /// current function.  The returned value is a member of the
1985 /// MachineJumpTableInfo::JTEntryKind enum.
1986 unsigned X86TargetLowering::getJumpTableEncoding() const {
1987   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1988   // symbol.
1989   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1990       Subtarget->isPICStyleGOT())
1991     return MachineJumpTableInfo::EK_Custom32;
1992
1993   // Otherwise, use the normal jump table encoding heuristics.
1994   return TargetLowering::getJumpTableEncoding();
1995 }
1996
1997 bool X86TargetLowering::useSoftFloat() const {
1998   return Subtarget->useSoftFloat();
1999 }
2000
2001 const MCExpr *
2002 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2003                                              const MachineBasicBlock *MBB,
2004                                              unsigned uid,MCContext &Ctx) const{
2005   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2006          Subtarget->isPICStyleGOT());
2007   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2008   // entries.
2009   return MCSymbolRefExpr::create(MBB->getSymbol(),
2010                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2011 }
2012
2013 /// Returns relocation base for the given PIC jumptable.
2014 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2015                                                     SelectionDAG &DAG) const {
2016   if (!Subtarget->is64Bit())
2017     // This doesn't have SDLoc associated with it, but is not really the
2018     // same as a Register.
2019     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2020                        getPointerTy(DAG.getDataLayout()));
2021   return Table;
2022 }
2023
2024 /// This returns the relocation base for the given PIC jumptable,
2025 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2026 const MCExpr *X86TargetLowering::
2027 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2028                              MCContext &Ctx) const {
2029   // X86-64 uses RIP relative addressing based on the jump table label.
2030   if (Subtarget->isPICStyleRIPRel())
2031     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2032
2033   // Otherwise, the reference is relative to the PIC base.
2034   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2035 }
2036
2037 std::pair<const TargetRegisterClass *, uint8_t>
2038 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2039                                            MVT VT) const {
2040   const TargetRegisterClass *RRC = nullptr;
2041   uint8_t Cost = 1;
2042   switch (VT.SimpleTy) {
2043   default:
2044     return TargetLowering::findRepresentativeClass(TRI, VT);
2045   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2046     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2047     break;
2048   case MVT::x86mmx:
2049     RRC = &X86::VR64RegClass;
2050     break;
2051   case MVT::f32: case MVT::f64:
2052   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2053   case MVT::v4f32: case MVT::v2f64:
2054   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2055   case MVT::v4f64:
2056     RRC = &X86::VR128RegClass;
2057     break;
2058   }
2059   return std::make_pair(RRC, Cost);
2060 }
2061
2062 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2063                                                unsigned &Offset) const {
2064   if (!Subtarget->isTargetLinux())
2065     return false;
2066
2067   if (Subtarget->is64Bit()) {
2068     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2069     Offset = 0x28;
2070     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2071       AddressSpace = 256;
2072     else
2073       AddressSpace = 257;
2074   } else {
2075     // %gs:0x14 on i386
2076     Offset = 0x14;
2077     AddressSpace = 256;
2078   }
2079   return true;
2080 }
2081
2082 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2083                                             unsigned DestAS) const {
2084   assert(SrcAS != DestAS && "Expected different address spaces!");
2085
2086   return SrcAS < 256 && DestAS < 256;
2087 }
2088
2089 //===----------------------------------------------------------------------===//
2090 //               Return Value Calling Convention Implementation
2091 //===----------------------------------------------------------------------===//
2092
2093 #include "X86GenCallingConv.inc"
2094
2095 bool X86TargetLowering::CanLowerReturn(
2096     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2097     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2098   SmallVector<CCValAssign, 16> RVLocs;
2099   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2100   return CCInfo.CheckReturn(Outs, RetCC_X86);
2101 }
2102
2103 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2104   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2105   return ScratchRegs;
2106 }
2107
2108 SDValue
2109 X86TargetLowering::LowerReturn(SDValue Chain,
2110                                CallingConv::ID CallConv, bool isVarArg,
2111                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2112                                const SmallVectorImpl<SDValue> &OutVals,
2113                                SDLoc dl, SelectionDAG &DAG) const {
2114   MachineFunction &MF = DAG.getMachineFunction();
2115   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2116
2117   SmallVector<CCValAssign, 16> RVLocs;
2118   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2119   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2120
2121   SDValue Flag;
2122   SmallVector<SDValue, 6> RetOps;
2123   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2124   // Operand #1 = Bytes To Pop
2125   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2126                    MVT::i16));
2127
2128   // Copy the result values into the output registers.
2129   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2130     CCValAssign &VA = RVLocs[i];
2131     assert(VA.isRegLoc() && "Can only return in registers!");
2132     SDValue ValToCopy = OutVals[i];
2133     EVT ValVT = ValToCopy.getValueType();
2134
2135     // Promote values to the appropriate types.
2136     if (VA.getLocInfo() == CCValAssign::SExt)
2137       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2138     else if (VA.getLocInfo() == CCValAssign::ZExt)
2139       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2140     else if (VA.getLocInfo() == CCValAssign::AExt) {
2141       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2142         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2143       else
2144         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2145     }
2146     else if (VA.getLocInfo() == CCValAssign::BCvt)
2147       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2148
2149     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2150            "Unexpected FP-extend for return value.");
2151
2152     // If this is x86-64, and we disabled SSE, we can't return FP values,
2153     // or SSE or MMX vectors.
2154     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2155          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2156           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2157       report_fatal_error("SSE register return with SSE disabled");
2158     }
2159     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2160     // llvm-gcc has never done it right and no one has noticed, so this
2161     // should be OK for now.
2162     if (ValVT == MVT::f64 &&
2163         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2164       report_fatal_error("SSE2 register return with SSE2 disabled");
2165
2166     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2167     // the RET instruction and handled by the FP Stackifier.
2168     if (VA.getLocReg() == X86::FP0 ||
2169         VA.getLocReg() == X86::FP1) {
2170       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2171       // change the value to the FP stack register class.
2172       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2173         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2174       RetOps.push_back(ValToCopy);
2175       // Don't emit a copytoreg.
2176       continue;
2177     }
2178
2179     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2180     // which is returned in RAX / RDX.
2181     if (Subtarget->is64Bit()) {
2182       if (ValVT == MVT::x86mmx) {
2183         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2184           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2185           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2186                                   ValToCopy);
2187           // If we don't have SSE2 available, convert to v4f32 so the generated
2188           // register is legal.
2189           if (!Subtarget->hasSSE2())
2190             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2191         }
2192       }
2193     }
2194
2195     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2196     Flag = Chain.getValue(1);
2197     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2198   }
2199
2200   // All x86 ABIs require that for returning structs by value we copy
2201   // the sret argument into %rax/%eax (depending on ABI) for the return.
2202   // We saved the argument into a virtual register in the entry block,
2203   // so now we copy the value out and into %rax/%eax.
2204   //
2205   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2206   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2207   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2208   // either case FuncInfo->setSRetReturnReg() will have been called.
2209   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2210     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2211                                      getPointerTy(MF.getDataLayout()));
2212
2213     unsigned RetValReg
2214         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2215           X86::RAX : X86::EAX;
2216     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2217     Flag = Chain.getValue(1);
2218
2219     // RAX/EAX now acts like a return value.
2220     RetOps.push_back(
2221         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2222   }
2223
2224   RetOps[0] = Chain;  // Update chain.
2225
2226   // Add the flag if we have it.
2227   if (Flag.getNode())
2228     RetOps.push_back(Flag);
2229
2230   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2231 }
2232
2233 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2234   if (N->getNumValues() != 1)
2235     return false;
2236   if (!N->hasNUsesOfValue(1, 0))
2237     return false;
2238
2239   SDValue TCChain = Chain;
2240   SDNode *Copy = *N->use_begin();
2241   if (Copy->getOpcode() == ISD::CopyToReg) {
2242     // If the copy has a glue operand, we conservatively assume it isn't safe to
2243     // perform a tail call.
2244     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2245       return false;
2246     TCChain = Copy->getOperand(0);
2247   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2248     return false;
2249
2250   bool HasRet = false;
2251   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2252        UI != UE; ++UI) {
2253     if (UI->getOpcode() != X86ISD::RET_FLAG)
2254       return false;
2255     // If we are returning more than one value, we can definitely
2256     // not make a tail call see PR19530
2257     if (UI->getNumOperands() > 4)
2258       return false;
2259     if (UI->getNumOperands() == 4 &&
2260         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2261       return false;
2262     HasRet = true;
2263   }
2264
2265   if (!HasRet)
2266     return false;
2267
2268   Chain = TCChain;
2269   return true;
2270 }
2271
2272 EVT
2273 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2274                                             ISD::NodeType ExtendKind) const {
2275   MVT ReturnMVT;
2276   // TODO: Is this also valid on 32-bit?
2277   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2278     ReturnMVT = MVT::i8;
2279   else
2280     ReturnMVT = MVT::i32;
2281
2282   EVT MinVT = getRegisterType(Context, ReturnMVT);
2283   return VT.bitsLT(MinVT) ? MinVT : VT;
2284 }
2285
2286 /// Lower the result values of a call into the
2287 /// appropriate copies out of appropriate physical registers.
2288 ///
2289 SDValue
2290 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2291                                    CallingConv::ID CallConv, bool isVarArg,
2292                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2293                                    SDLoc dl, SelectionDAG &DAG,
2294                                    SmallVectorImpl<SDValue> &InVals) const {
2295
2296   // Assign locations to each value returned by this call.
2297   SmallVector<CCValAssign, 16> RVLocs;
2298   bool Is64Bit = Subtarget->is64Bit();
2299   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2300                  *DAG.getContext());
2301   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2302
2303   // Copy all of the result registers out of their specified physreg.
2304   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2305     CCValAssign &VA = RVLocs[i];
2306     EVT CopyVT = VA.getLocVT();
2307
2308     // If this is x86-64, and we disabled SSE, we can't return FP values
2309     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2310         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2311       report_fatal_error("SSE register return with SSE disabled");
2312     }
2313
2314     // If we prefer to use the value in xmm registers, copy it out as f80 and
2315     // use a truncate to move it from fp stack reg to xmm reg.
2316     bool RoundAfterCopy = false;
2317     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2318         isScalarFPTypeInSSEReg(VA.getValVT())) {
2319       CopyVT = MVT::f80;
2320       RoundAfterCopy = (CopyVT != VA.getLocVT());
2321     }
2322
2323     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2324                                CopyVT, InFlag).getValue(1);
2325     SDValue Val = Chain.getValue(0);
2326
2327     if (RoundAfterCopy)
2328       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2329                         // This truncation won't change the value.
2330                         DAG.getIntPtrConstant(1, dl));
2331
2332     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2333       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2334
2335     InFlag = Chain.getValue(2);
2336     InVals.push_back(Val);
2337   }
2338
2339   return Chain;
2340 }
2341
2342 //===----------------------------------------------------------------------===//
2343 //                C & StdCall & Fast Calling Convention implementation
2344 //===----------------------------------------------------------------------===//
2345 //  StdCall calling convention seems to be standard for many Windows' API
2346 //  routines and around. It differs from C calling convention just a little:
2347 //  callee should clean up the stack, not caller. Symbols should be also
2348 //  decorated in some fancy way :) It doesn't support any vector arguments.
2349 //  For info on fast calling convention see Fast Calling Convention (tail call)
2350 //  implementation LowerX86_32FastCCCallTo.
2351
2352 /// CallIsStructReturn - Determines whether a call uses struct return
2353 /// semantics.
2354 enum StructReturnType {
2355   NotStructReturn,
2356   RegStructReturn,
2357   StackStructReturn
2358 };
2359 static StructReturnType
2360 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2361   if (Outs.empty())
2362     return NotStructReturn;
2363
2364   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2365   if (!Flags.isSRet())
2366     return NotStructReturn;
2367   if (Flags.isInReg())
2368     return RegStructReturn;
2369   return StackStructReturn;
2370 }
2371
2372 /// Determines whether a function uses struct return semantics.
2373 static StructReturnType
2374 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2375   if (Ins.empty())
2376     return NotStructReturn;
2377
2378   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2379   if (!Flags.isSRet())
2380     return NotStructReturn;
2381   if (Flags.isInReg())
2382     return RegStructReturn;
2383   return StackStructReturn;
2384 }
2385
2386 /// Make a copy of an aggregate at address specified by "Src" to address
2387 /// "Dst" with size and alignment information specified by the specific
2388 /// parameter attribute. The copy will be passed as a byval function parameter.
2389 static SDValue
2390 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2391                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2392                           SDLoc dl) {
2393   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2394
2395   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2396                        /*isVolatile*/false, /*AlwaysInline=*/true,
2397                        /*isTailCall*/false,
2398                        MachinePointerInfo(), MachinePointerInfo());
2399 }
2400
2401 /// Return true if the calling convention is one that
2402 /// supports tail call optimization.
2403 static bool IsTailCallConvention(CallingConv::ID CC) {
2404   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2405           CC == CallingConv::HiPE);
2406 }
2407
2408 /// \brief Return true if the calling convention is a C calling convention.
2409 static bool IsCCallConvention(CallingConv::ID CC) {
2410   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2411           CC == CallingConv::X86_64_SysV);
2412 }
2413
2414 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2415   auto Attr =
2416       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2417   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2418     return false;
2419
2420   CallSite CS(CI);
2421   CallingConv::ID CalleeCC = CS.getCallingConv();
2422   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2423     return false;
2424
2425   return true;
2426 }
2427
2428 /// Return true if the function is being made into
2429 /// a tailcall target by changing its ABI.
2430 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2431                                    bool GuaranteedTailCallOpt) {
2432   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2433 }
2434
2435 SDValue
2436 X86TargetLowering::LowerMemArgument(SDValue Chain,
2437                                     CallingConv::ID CallConv,
2438                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2439                                     SDLoc dl, SelectionDAG &DAG,
2440                                     const CCValAssign &VA,
2441                                     MachineFrameInfo *MFI,
2442                                     unsigned i) const {
2443   // Create the nodes corresponding to a load from this parameter slot.
2444   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2445   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2446       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2447   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2448   EVT ValVT;
2449
2450   // If value is passed by pointer we have address passed instead of the value
2451   // itself.
2452   bool ExtendedInMem = VA.isExtInLoc() &&
2453     VA.getValVT().getScalarType() == MVT::i1;
2454
2455   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2456     ValVT = VA.getLocVT();
2457   else
2458     ValVT = VA.getValVT();
2459
2460   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2461   // changed with more analysis.
2462   // In case of tail call optimization mark all arguments mutable. Since they
2463   // could be overwritten by lowering of arguments in case of a tail call.
2464   if (Flags.isByVal()) {
2465     unsigned Bytes = Flags.getByValSize();
2466     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2467     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2468     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2469   } else {
2470     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2471                                     VA.getLocMemOffset(), isImmutable);
2472     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2473     SDValue Val = DAG.getLoad(
2474         ValVT, dl, Chain, FIN,
2475         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2476         false, false, 0);
2477     return ExtendedInMem ?
2478       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2479   }
2480 }
2481
2482 // FIXME: Get this from tablegen.
2483 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2484                                                 const X86Subtarget *Subtarget) {
2485   assert(Subtarget->is64Bit());
2486
2487   if (Subtarget->isCallingConvWin64(CallConv)) {
2488     static const MCPhysReg GPR64ArgRegsWin64[] = {
2489       X86::RCX, X86::RDX, X86::R8,  X86::R9
2490     };
2491     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2492   }
2493
2494   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2495     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2496   };
2497   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2498 }
2499
2500 // FIXME: Get this from tablegen.
2501 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2502                                                 CallingConv::ID CallConv,
2503                                                 const X86Subtarget *Subtarget) {
2504   assert(Subtarget->is64Bit());
2505   if (Subtarget->isCallingConvWin64(CallConv)) {
2506     // The XMM registers which might contain var arg parameters are shadowed
2507     // in their paired GPR.  So we only need to save the GPR to their home
2508     // slots.
2509     // TODO: __vectorcall will change this.
2510     return None;
2511   }
2512
2513   const Function *Fn = MF.getFunction();
2514   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2515   bool isSoftFloat = Subtarget->useSoftFloat();
2516   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2517          "SSE register cannot be used when SSE is disabled!");
2518   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2519     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2520     // registers.
2521     return None;
2522
2523   static const MCPhysReg XMMArgRegs64Bit[] = {
2524     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2525     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2526   };
2527   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2528 }
2529
2530 SDValue X86TargetLowering::LowerFormalArguments(
2531     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2532     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2533     SmallVectorImpl<SDValue> &InVals) const {
2534   MachineFunction &MF = DAG.getMachineFunction();
2535   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2536   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2537
2538   const Function* Fn = MF.getFunction();
2539   if (Fn->hasExternalLinkage() &&
2540       Subtarget->isTargetCygMing() &&
2541       Fn->getName() == "main")
2542     FuncInfo->setForceFramePointer(true);
2543
2544   MachineFrameInfo *MFI = MF.getFrameInfo();
2545   bool Is64Bit = Subtarget->is64Bit();
2546   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2547
2548   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2549          "Var args not supported with calling convention fastcc, ghc or hipe");
2550
2551   // Assign locations to all of the incoming arguments.
2552   SmallVector<CCValAssign, 16> ArgLocs;
2553   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2554
2555   // Allocate shadow area for Win64
2556   if (IsWin64)
2557     CCInfo.AllocateStack(32, 8);
2558
2559   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2560
2561   unsigned LastVal = ~0U;
2562   SDValue ArgValue;
2563   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2564     CCValAssign &VA = ArgLocs[i];
2565     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2566     // places.
2567     assert(VA.getValNo() != LastVal &&
2568            "Don't support value assigned to multiple locs yet");
2569     (void)LastVal;
2570     LastVal = VA.getValNo();
2571
2572     if (VA.isRegLoc()) {
2573       EVT RegVT = VA.getLocVT();
2574       const TargetRegisterClass *RC;
2575       if (RegVT == MVT::i32)
2576         RC = &X86::GR32RegClass;
2577       else if (Is64Bit && RegVT == MVT::i64)
2578         RC = &X86::GR64RegClass;
2579       else if (RegVT == MVT::f32)
2580         RC = &X86::FR32RegClass;
2581       else if (RegVT == MVT::f64)
2582         RC = &X86::FR64RegClass;
2583       else if (RegVT.is512BitVector())
2584         RC = &X86::VR512RegClass;
2585       else if (RegVT.is256BitVector())
2586         RC = &X86::VR256RegClass;
2587       else if (RegVT.is128BitVector())
2588         RC = &X86::VR128RegClass;
2589       else if (RegVT == MVT::x86mmx)
2590         RC = &X86::VR64RegClass;
2591       else if (RegVT == MVT::i1)
2592         RC = &X86::VK1RegClass;
2593       else if (RegVT == MVT::v8i1)
2594         RC = &X86::VK8RegClass;
2595       else if (RegVT == MVT::v16i1)
2596         RC = &X86::VK16RegClass;
2597       else if (RegVT == MVT::v32i1)
2598         RC = &X86::VK32RegClass;
2599       else if (RegVT == MVT::v64i1)
2600         RC = &X86::VK64RegClass;
2601       else
2602         llvm_unreachable("Unknown argument type!");
2603
2604       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2605       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2606
2607       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2608       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2609       // right size.
2610       if (VA.getLocInfo() == CCValAssign::SExt)
2611         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2612                                DAG.getValueType(VA.getValVT()));
2613       else if (VA.getLocInfo() == CCValAssign::ZExt)
2614         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2615                                DAG.getValueType(VA.getValVT()));
2616       else if (VA.getLocInfo() == CCValAssign::BCvt)
2617         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2618
2619       if (VA.isExtInLoc()) {
2620         // Handle MMX values passed in XMM regs.
2621         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2622           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2623         else
2624           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2625       }
2626     } else {
2627       assert(VA.isMemLoc());
2628       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2629     }
2630
2631     // If value is passed via pointer - do a load.
2632     if (VA.getLocInfo() == CCValAssign::Indirect)
2633       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2634                              MachinePointerInfo(), false, false, false, 0);
2635
2636     InVals.push_back(ArgValue);
2637   }
2638
2639   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2640     // All x86 ABIs require that for returning structs by value we copy the
2641     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2642     // the argument into a virtual register so that we can access it from the
2643     // return points.
2644     if (Ins[i].Flags.isSRet()) {
2645       unsigned Reg = FuncInfo->getSRetReturnReg();
2646       if (!Reg) {
2647         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2648         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2649         FuncInfo->setSRetReturnReg(Reg);
2650       }
2651       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2652       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2653       break;
2654     }
2655   }
2656
2657   unsigned StackSize = CCInfo.getNextStackOffset();
2658   // Align stack specially for tail calls.
2659   if (FuncIsMadeTailCallSafe(CallConv,
2660                              MF.getTarget().Options.GuaranteedTailCallOpt))
2661     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2662
2663   // If the function takes variable number of arguments, make a frame index for
2664   // the start of the first vararg value... for expansion of llvm.va_start. We
2665   // can skip this if there are no va_start calls.
2666   if (MFI->hasVAStart() &&
2667       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2668                    CallConv != CallingConv::X86_ThisCall))) {
2669     FuncInfo->setVarArgsFrameIndex(
2670         MFI->CreateFixedObject(1, StackSize, true));
2671   }
2672
2673   MachineModuleInfo &MMI = MF.getMMI();
2674   const Function *WinEHParent = nullptr;
2675   if (MMI.hasWinEHFuncInfo(Fn))
2676     WinEHParent = MMI.getWinEHParent(Fn);
2677   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2678
2679   // Figure out if XMM registers are in use.
2680   assert(!(Subtarget->useSoftFloat() &&
2681            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2682          "SSE register cannot be used when SSE is disabled!");
2683
2684   // 64-bit calling conventions support varargs and register parameters, so we
2685   // have to do extra work to spill them in the prologue.
2686   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2687     // Find the first unallocated argument registers.
2688     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2689     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2690     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2691     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2692     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2693            "SSE register cannot be used when SSE is disabled!");
2694
2695     // Gather all the live in physical registers.
2696     SmallVector<SDValue, 6> LiveGPRs;
2697     SmallVector<SDValue, 8> LiveXMMRegs;
2698     SDValue ALVal;
2699     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2700       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2701       LiveGPRs.push_back(
2702           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2703     }
2704     if (!ArgXMMs.empty()) {
2705       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2706       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2707       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2708         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2709         LiveXMMRegs.push_back(
2710             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2711       }
2712     }
2713
2714     if (IsWin64) {
2715       // Get to the caller-allocated home save location.  Add 8 to account
2716       // for the return address.
2717       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2718       FuncInfo->setRegSaveFrameIndex(
2719           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2720       // Fixup to set vararg frame on shadow area (4 x i64).
2721       if (NumIntRegs < 4)
2722         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2723     } else {
2724       // For X86-64, if there are vararg parameters that are passed via
2725       // registers, then we must store them to their spots on the stack so
2726       // they may be loaded by deferencing the result of va_next.
2727       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2728       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2729       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2730           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2731     }
2732
2733     // Store the integer parameter registers.
2734     SmallVector<SDValue, 8> MemOps;
2735     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2736                                       getPointerTy(DAG.getDataLayout()));
2737     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2738     for (SDValue Val : LiveGPRs) {
2739       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2740                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2741       SDValue Store =
2742           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2743                        MachinePointerInfo::getFixedStack(
2744                            DAG.getMachineFunction(),
2745                            FuncInfo->getRegSaveFrameIndex(), Offset),
2746                        false, false, 0);
2747       MemOps.push_back(Store);
2748       Offset += 8;
2749     }
2750
2751     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2752       // Now store the XMM (fp + vector) parameter registers.
2753       SmallVector<SDValue, 12> SaveXMMOps;
2754       SaveXMMOps.push_back(Chain);
2755       SaveXMMOps.push_back(ALVal);
2756       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2757                              FuncInfo->getRegSaveFrameIndex(), dl));
2758       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2759                              FuncInfo->getVarArgsFPOffset(), dl));
2760       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2761                         LiveXMMRegs.end());
2762       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2763                                    MVT::Other, SaveXMMOps));
2764     }
2765
2766     if (!MemOps.empty())
2767       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2768   }
2769
2770   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2771     // Find the largest legal vector type.
2772     MVT VecVT = MVT::Other;
2773     // FIXME: Only some x86_32 calling conventions support AVX512.
2774     if (Subtarget->hasAVX512() &&
2775         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2776                      CallConv == CallingConv::Intel_OCL_BI)))
2777       VecVT = MVT::v16f32;
2778     else if (Subtarget->hasAVX())
2779       VecVT = MVT::v8f32;
2780     else if (Subtarget->hasSSE2())
2781       VecVT = MVT::v4f32;
2782
2783     // We forward some GPRs and some vector types.
2784     SmallVector<MVT, 2> RegParmTypes;
2785     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2786     RegParmTypes.push_back(IntVT);
2787     if (VecVT != MVT::Other)
2788       RegParmTypes.push_back(VecVT);
2789
2790     // Compute the set of forwarded registers. The rest are scratch.
2791     SmallVectorImpl<ForwardedRegister> &Forwards =
2792         FuncInfo->getForwardedMustTailRegParms();
2793     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2794
2795     // Conservatively forward AL on x86_64, since it might be used for varargs.
2796     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2797       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2798       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2799     }
2800
2801     // Copy all forwards from physical to virtual registers.
2802     for (ForwardedRegister &F : Forwards) {
2803       // FIXME: Can we use a less constrained schedule?
2804       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2805       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2806       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2807     }
2808   }
2809
2810   // Some CCs need callee pop.
2811   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2812                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2813     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2814   } else {
2815     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2816     // If this is an sret function, the return should pop the hidden pointer.
2817     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2818         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2819         argsAreStructReturn(Ins) == StackStructReturn)
2820       FuncInfo->setBytesToPopOnReturn(4);
2821   }
2822
2823   if (!Is64Bit) {
2824     // RegSaveFrameIndex is X86-64 only.
2825     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2826     if (CallConv == CallingConv::X86_FastCall ||
2827         CallConv == CallingConv::X86_ThisCall)
2828       // fastcc functions can't have varargs.
2829       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2830   }
2831
2832   FuncInfo->setArgumentStackSize(StackSize);
2833
2834   if (IsWinEHParent) {
2835     if (Is64Bit) {
2836       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2837       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2838       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2839       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2840       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2841                            MachinePointerInfo::getFixedStack(
2842                                DAG.getMachineFunction(), UnwindHelpFI),
2843                            /*isVolatile=*/true,
2844                            /*isNonTemporal=*/false, /*Alignment=*/0);
2845     } else {
2846       // Functions using Win32 EH are considered to have opaque SP adjustments
2847       // to force local variables to be addressed from the frame or base
2848       // pointers.
2849       MFI->setHasOpaqueSPAdjustment(true);
2850     }
2851   }
2852
2853   return Chain;
2854 }
2855
2856 SDValue
2857 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2858                                     SDValue StackPtr, SDValue Arg,
2859                                     SDLoc dl, SelectionDAG &DAG,
2860                                     const CCValAssign &VA,
2861                                     ISD::ArgFlagsTy Flags) const {
2862   unsigned LocMemOffset = VA.getLocMemOffset();
2863   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2864   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2865                        StackPtr, PtrOff);
2866   if (Flags.isByVal())
2867     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2868
2869   return DAG.getStore(
2870       Chain, dl, Arg, PtrOff,
2871       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2872       false, false, 0);
2873 }
2874
2875 /// Emit a load of return address if tail call
2876 /// optimization is performed and it is required.
2877 SDValue
2878 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2879                                            SDValue &OutRetAddr, SDValue Chain,
2880                                            bool IsTailCall, bool Is64Bit,
2881                                            int FPDiff, SDLoc dl) const {
2882   // Adjust the Return address stack slot.
2883   EVT VT = getPointerTy(DAG.getDataLayout());
2884   OutRetAddr = getReturnAddressFrameIndex(DAG);
2885
2886   // Load the "old" Return address.
2887   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2888                            false, false, false, 0);
2889   return SDValue(OutRetAddr.getNode(), 1);
2890 }
2891
2892 /// Emit a store of the return address if tail call
2893 /// optimization is performed and it is required (FPDiff!=0).
2894 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2895                                         SDValue Chain, SDValue RetAddrFrIdx,
2896                                         EVT PtrVT, unsigned SlotSize,
2897                                         int FPDiff, SDLoc dl) {
2898   // Store the return address to the appropriate stack slot.
2899   if (!FPDiff) return Chain;
2900   // Calculate the new stack slot for the return address.
2901   int NewReturnAddrFI =
2902     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2903                                          false);
2904   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2905   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2906                        MachinePointerInfo::getFixedStack(
2907                            DAG.getMachineFunction(), NewReturnAddrFI),
2908                        false, false, 0);
2909   return Chain;
2910 }
2911
2912 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2913 /// operation of specified width.
2914 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2915                        SDValue V2) {
2916   unsigned NumElems = VT.getVectorNumElements();
2917   SmallVector<int, 8> Mask;
2918   Mask.push_back(NumElems);
2919   for (unsigned i = 1; i != NumElems; ++i)
2920     Mask.push_back(i);
2921   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2922 }
2923
2924 SDValue
2925 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2926                              SmallVectorImpl<SDValue> &InVals) const {
2927   SelectionDAG &DAG                     = CLI.DAG;
2928   SDLoc &dl                             = CLI.DL;
2929   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2930   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2931   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2932   SDValue Chain                         = CLI.Chain;
2933   SDValue Callee                        = CLI.Callee;
2934   CallingConv::ID CallConv              = CLI.CallConv;
2935   bool &isTailCall                      = CLI.IsTailCall;
2936   bool isVarArg                         = CLI.IsVarArg;
2937
2938   MachineFunction &MF = DAG.getMachineFunction();
2939   bool Is64Bit        = Subtarget->is64Bit();
2940   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2941   StructReturnType SR = callIsStructReturn(Outs);
2942   bool IsSibcall      = false;
2943   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2944   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2945
2946   if (Attr.getValueAsString() == "true")
2947     isTailCall = false;
2948
2949   if (Subtarget->isPICStyleGOT() &&
2950       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2951     // If we are using a GOT, disable tail calls to external symbols with
2952     // default visibility. Tail calling such a symbol requires using a GOT
2953     // relocation, which forces early binding of the symbol. This breaks code
2954     // that require lazy function symbol resolution. Using musttail or
2955     // GuaranteedTailCallOpt will override this.
2956     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2957     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2958                G->getGlobal()->hasDefaultVisibility()))
2959       isTailCall = false;
2960   }
2961
2962   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2963   if (IsMustTail) {
2964     // Force this to be a tail call.  The verifier rules are enough to ensure
2965     // that we can lower this successfully without moving the return address
2966     // around.
2967     isTailCall = true;
2968   } else if (isTailCall) {
2969     // Check if it's really possible to do a tail call.
2970     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2971                     isVarArg, SR != NotStructReturn,
2972                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2973                     Outs, OutVals, Ins, DAG);
2974
2975     // Sibcalls are automatically detected tailcalls which do not require
2976     // ABI changes.
2977     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2978       IsSibcall = true;
2979
2980     if (isTailCall)
2981       ++NumTailCalls;
2982   }
2983
2984   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2985          "Var args not supported with calling convention fastcc, ghc or hipe");
2986
2987   // Analyze operands of the call, assigning locations to each operand.
2988   SmallVector<CCValAssign, 16> ArgLocs;
2989   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2990
2991   // Allocate shadow area for Win64
2992   if (IsWin64)
2993     CCInfo.AllocateStack(32, 8);
2994
2995   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2996
2997   // Get a count of how many bytes are to be pushed on the stack.
2998   unsigned NumBytes = CCInfo.getNextStackOffset();
2999   if (IsSibcall)
3000     // This is a sibcall. The memory operands are available in caller's
3001     // own caller's stack.
3002     NumBytes = 0;
3003   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3004            IsTailCallConvention(CallConv))
3005     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3006
3007   int FPDiff = 0;
3008   if (isTailCall && !IsSibcall && !IsMustTail) {
3009     // Lower arguments at fp - stackoffset + fpdiff.
3010     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3011
3012     FPDiff = NumBytesCallerPushed - NumBytes;
3013
3014     // Set the delta of movement of the returnaddr stackslot.
3015     // But only set if delta is greater than previous delta.
3016     if (FPDiff < X86Info->getTCReturnAddrDelta())
3017       X86Info->setTCReturnAddrDelta(FPDiff);
3018   }
3019
3020   unsigned NumBytesToPush = NumBytes;
3021   unsigned NumBytesToPop = NumBytes;
3022
3023   // If we have an inalloca argument, all stack space has already been allocated
3024   // for us and be right at the top of the stack.  We don't support multiple
3025   // arguments passed in memory when using inalloca.
3026   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3027     NumBytesToPush = 0;
3028     if (!ArgLocs.back().isMemLoc())
3029       report_fatal_error("cannot use inalloca attribute on a register "
3030                          "parameter");
3031     if (ArgLocs.back().getLocMemOffset() != 0)
3032       report_fatal_error("any parameter with the inalloca attribute must be "
3033                          "the only memory argument");
3034   }
3035
3036   if (!IsSibcall)
3037     Chain = DAG.getCALLSEQ_START(
3038         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3039
3040   SDValue RetAddrFrIdx;
3041   // Load return address for tail calls.
3042   if (isTailCall && FPDiff)
3043     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3044                                     Is64Bit, FPDiff, dl);
3045
3046   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3047   SmallVector<SDValue, 8> MemOpChains;
3048   SDValue StackPtr;
3049
3050   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3051   // of tail call optimization arguments are handle later.
3052   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3053   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3054     // Skip inalloca arguments, they have already been written.
3055     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3056     if (Flags.isInAlloca())
3057       continue;
3058
3059     CCValAssign &VA = ArgLocs[i];
3060     EVT RegVT = VA.getLocVT();
3061     SDValue Arg = OutVals[i];
3062     bool isByVal = Flags.isByVal();
3063
3064     // Promote the value if needed.
3065     switch (VA.getLocInfo()) {
3066     default: llvm_unreachable("Unknown loc info!");
3067     case CCValAssign::Full: break;
3068     case CCValAssign::SExt:
3069       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3070       break;
3071     case CCValAssign::ZExt:
3072       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3073       break;
3074     case CCValAssign::AExt:
3075       if (Arg.getValueType().isVector() &&
3076           Arg.getValueType().getScalarType() == MVT::i1)
3077         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3078       else if (RegVT.is128BitVector()) {
3079         // Special case: passing MMX values in XMM registers.
3080         Arg = DAG.getBitcast(MVT::i64, Arg);
3081         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3082         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3083       } else
3084         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3085       break;
3086     case CCValAssign::BCvt:
3087       Arg = DAG.getBitcast(RegVT, Arg);
3088       break;
3089     case CCValAssign::Indirect: {
3090       // Store the argument.
3091       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3092       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3093       Chain = DAG.getStore(
3094           Chain, dl, Arg, SpillSlot,
3095           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3096           false, false, 0);
3097       Arg = SpillSlot;
3098       break;
3099     }
3100     }
3101
3102     if (VA.isRegLoc()) {
3103       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3104       if (isVarArg && IsWin64) {
3105         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3106         // shadow reg if callee is a varargs function.
3107         unsigned ShadowReg = 0;
3108         switch (VA.getLocReg()) {
3109         case X86::XMM0: ShadowReg = X86::RCX; break;
3110         case X86::XMM1: ShadowReg = X86::RDX; break;
3111         case X86::XMM2: ShadowReg = X86::R8; break;
3112         case X86::XMM3: ShadowReg = X86::R9; break;
3113         }
3114         if (ShadowReg)
3115           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3116       }
3117     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3118       assert(VA.isMemLoc());
3119       if (!StackPtr.getNode())
3120         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3121                                       getPointerTy(DAG.getDataLayout()));
3122       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3123                                              dl, DAG, VA, Flags));
3124     }
3125   }
3126
3127   if (!MemOpChains.empty())
3128     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3129
3130   if (Subtarget->isPICStyleGOT()) {
3131     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3132     // GOT pointer.
3133     if (!isTailCall) {
3134       RegsToPass.push_back(std::make_pair(
3135           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3136                                           getPointerTy(DAG.getDataLayout()))));
3137     } else {
3138       // If we are tail calling and generating PIC/GOT style code load the
3139       // address of the callee into ECX. The value in ecx is used as target of
3140       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3141       // for tail calls on PIC/GOT architectures. Normally we would just put the
3142       // address of GOT into ebx and then call target@PLT. But for tail calls
3143       // ebx would be restored (since ebx is callee saved) before jumping to the
3144       // target@PLT.
3145
3146       // Note: The actual moving to ECX is done further down.
3147       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3148       if (G && !G->getGlobal()->hasLocalLinkage() &&
3149           G->getGlobal()->hasDefaultVisibility())
3150         Callee = LowerGlobalAddress(Callee, DAG);
3151       else if (isa<ExternalSymbolSDNode>(Callee))
3152         Callee = LowerExternalSymbol(Callee, DAG);
3153     }
3154   }
3155
3156   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3157     // From AMD64 ABI document:
3158     // For calls that may call functions that use varargs or stdargs
3159     // (prototype-less calls or calls to functions containing ellipsis (...) in
3160     // the declaration) %al is used as hidden argument to specify the number
3161     // of SSE registers used. The contents of %al do not need to match exactly
3162     // the number of registers, but must be an ubound on the number of SSE
3163     // registers used and is in the range 0 - 8 inclusive.
3164
3165     // Count the number of XMM registers allocated.
3166     static const MCPhysReg XMMArgRegs[] = {
3167       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3168       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3169     };
3170     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3171     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3172            && "SSE registers cannot be used when SSE is disabled");
3173
3174     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3175                                         DAG.getConstant(NumXMMRegs, dl,
3176                                                         MVT::i8)));
3177   }
3178
3179   if (isVarArg && IsMustTail) {
3180     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3181     for (const auto &F : Forwards) {
3182       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3183       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3184     }
3185   }
3186
3187   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3188   // don't need this because the eligibility check rejects calls that require
3189   // shuffling arguments passed in memory.
3190   if (!IsSibcall && isTailCall) {
3191     // Force all the incoming stack arguments to be loaded from the stack
3192     // before any new outgoing arguments are stored to the stack, because the
3193     // outgoing stack slots may alias the incoming argument stack slots, and
3194     // the alias isn't otherwise explicit. This is slightly more conservative
3195     // than necessary, because it means that each store effectively depends
3196     // on every argument instead of just those arguments it would clobber.
3197     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3198
3199     SmallVector<SDValue, 8> MemOpChains2;
3200     SDValue FIN;
3201     int FI = 0;
3202     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3203       CCValAssign &VA = ArgLocs[i];
3204       if (VA.isRegLoc())
3205         continue;
3206       assert(VA.isMemLoc());
3207       SDValue Arg = OutVals[i];
3208       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3209       // Skip inalloca arguments.  They don't require any work.
3210       if (Flags.isInAlloca())
3211         continue;
3212       // Create frame index.
3213       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3214       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3215       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3216       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3217
3218       if (Flags.isByVal()) {
3219         // Copy relative to framepointer.
3220         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3221         if (!StackPtr.getNode())
3222           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3223                                         getPointerTy(DAG.getDataLayout()));
3224         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3225                              StackPtr, Source);
3226
3227         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3228                                                          ArgChain,
3229                                                          Flags, DAG, dl));
3230       } else {
3231         // Store relative to framepointer.
3232         MemOpChains2.push_back(DAG.getStore(
3233             ArgChain, dl, Arg, FIN,
3234             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3235             false, false, 0));
3236       }
3237     }
3238
3239     if (!MemOpChains2.empty())
3240       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3241
3242     // Store the return address to the appropriate stack slot.
3243     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3244                                      getPointerTy(DAG.getDataLayout()),
3245                                      RegInfo->getSlotSize(), FPDiff, dl);
3246   }
3247
3248   // Build a sequence of copy-to-reg nodes chained together with token chain
3249   // and flag operands which copy the outgoing args into registers.
3250   SDValue InFlag;
3251   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3252     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3253                              RegsToPass[i].second, InFlag);
3254     InFlag = Chain.getValue(1);
3255   }
3256
3257   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3258     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3259     // In the 64-bit large code model, we have to make all calls
3260     // through a register, since the call instruction's 32-bit
3261     // pc-relative offset may not be large enough to hold the whole
3262     // address.
3263   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3264     // If the callee is a GlobalAddress node (quite common, every direct call
3265     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3266     // it.
3267     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3268
3269     // We should use extra load for direct calls to dllimported functions in
3270     // non-JIT mode.
3271     const GlobalValue *GV = G->getGlobal();
3272     if (!GV->hasDLLImportStorageClass()) {
3273       unsigned char OpFlags = 0;
3274       bool ExtraLoad = false;
3275       unsigned WrapperKind = ISD::DELETED_NODE;
3276
3277       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3278       // external symbols most go through the PLT in PIC mode.  If the symbol
3279       // has hidden or protected visibility, or if it is static or local, then
3280       // we don't need to use the PLT - we can directly call it.
3281       if (Subtarget->isTargetELF() &&
3282           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3283           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3284         OpFlags = X86II::MO_PLT;
3285       } else if (Subtarget->isPICStyleStubAny() &&
3286                  !GV->isStrongDefinitionForLinker() &&
3287                  (!Subtarget->getTargetTriple().isMacOSX() ||
3288                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3289         // PC-relative references to external symbols should go through $stub,
3290         // unless we're building with the leopard linker or later, which
3291         // automatically synthesizes these stubs.
3292         OpFlags = X86II::MO_DARWIN_STUB;
3293       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3294                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3295         // If the function is marked as non-lazy, generate an indirect call
3296         // which loads from the GOT directly. This avoids runtime overhead
3297         // at the cost of eager binding (and one extra byte of encoding).
3298         OpFlags = X86II::MO_GOTPCREL;
3299         WrapperKind = X86ISD::WrapperRIP;
3300         ExtraLoad = true;
3301       }
3302
3303       Callee = DAG.getTargetGlobalAddress(
3304           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3305
3306       // Add a wrapper if needed.
3307       if (WrapperKind != ISD::DELETED_NODE)
3308         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3309                              getPointerTy(DAG.getDataLayout()), Callee);
3310       // Add extra indirection if needed.
3311       if (ExtraLoad)
3312         Callee = DAG.getLoad(
3313             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3314             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3315             false, 0);
3316     }
3317   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3318     unsigned char OpFlags = 0;
3319
3320     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3321     // external symbols should go through the PLT.
3322     if (Subtarget->isTargetELF() &&
3323         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3324       OpFlags = X86II::MO_PLT;
3325     } else if (Subtarget->isPICStyleStubAny() &&
3326                (!Subtarget->getTargetTriple().isMacOSX() ||
3327                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3328       // PC-relative references to external symbols should go through $stub,
3329       // unless we're building with the leopard linker or later, which
3330       // automatically synthesizes these stubs.
3331       OpFlags = X86II::MO_DARWIN_STUB;
3332     }
3333
3334     Callee = DAG.getTargetExternalSymbol(
3335         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3336   } else if (Subtarget->isTarget64BitILP32() &&
3337              Callee->getValueType(0) == MVT::i32) {
3338     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3339     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3340   }
3341
3342   // Returns a chain & a flag for retval copy to use.
3343   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3344   SmallVector<SDValue, 8> Ops;
3345
3346   if (!IsSibcall && isTailCall) {
3347     Chain = DAG.getCALLSEQ_END(Chain,
3348                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3349                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3350     InFlag = Chain.getValue(1);
3351   }
3352
3353   Ops.push_back(Chain);
3354   Ops.push_back(Callee);
3355
3356   if (isTailCall)
3357     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3358
3359   // Add argument registers to the end of the list so that they are known live
3360   // into the call.
3361   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3362     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3363                                   RegsToPass[i].second.getValueType()));
3364
3365   // Add a register mask operand representing the call-preserved registers.
3366   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3367   assert(Mask && "Missing call preserved mask for calling convention");
3368
3369   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3370   // the function clobbers all registers. If an exception is thrown, the runtime
3371   // will not restore CSRs.
3372   // FIXME: Model this more precisely so that we can register allocate across
3373   // the normal edge and spill and fill across the exceptional edge.
3374   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3375     const Function *CallerFn = MF.getFunction();
3376     EHPersonality Pers =
3377         CallerFn->hasPersonalityFn()
3378             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3379             : EHPersonality::Unknown;
3380     if (isMSVCEHPersonality(Pers))
3381       Mask = RegInfo->getNoPreservedMask();
3382   }
3383
3384   Ops.push_back(DAG.getRegisterMask(Mask));
3385
3386   if (InFlag.getNode())
3387     Ops.push_back(InFlag);
3388
3389   if (isTailCall) {
3390     // We used to do:
3391     //// If this is the first return lowered for this function, add the regs
3392     //// to the liveout set for the function.
3393     // This isn't right, although it's probably harmless on x86; liveouts
3394     // should be computed from returns not tail calls.  Consider a void
3395     // function making a tail call to a function returning int.
3396     MF.getFrameInfo()->setHasTailCall();
3397     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3398   }
3399
3400   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3401   InFlag = Chain.getValue(1);
3402
3403   // Create the CALLSEQ_END node.
3404   unsigned NumBytesForCalleeToPop;
3405   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3406                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3407     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3408   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3409            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3410            SR == StackStructReturn)
3411     // If this is a call to a struct-return function, the callee
3412     // pops the hidden struct pointer, so we have to push it back.
3413     // This is common for Darwin/X86, Linux & Mingw32 targets.
3414     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3415     NumBytesForCalleeToPop = 4;
3416   else
3417     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3418
3419   // Returns a flag for retval copy to use.
3420   if (!IsSibcall) {
3421     Chain = DAG.getCALLSEQ_END(Chain,
3422                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3423                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3424                                                      true),
3425                                InFlag, dl);
3426     InFlag = Chain.getValue(1);
3427   }
3428
3429   // Handle result values, copying them out of physregs into vregs that we
3430   // return.
3431   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3432                          Ins, dl, DAG, InVals);
3433 }
3434
3435 //===----------------------------------------------------------------------===//
3436 //                Fast Calling Convention (tail call) implementation
3437 //===----------------------------------------------------------------------===//
3438
3439 //  Like std call, callee cleans arguments, convention except that ECX is
3440 //  reserved for storing the tail called function address. Only 2 registers are
3441 //  free for argument passing (inreg). Tail call optimization is performed
3442 //  provided:
3443 //                * tailcallopt is enabled
3444 //                * caller/callee are fastcc
3445 //  On X86_64 architecture with GOT-style position independent code only local
3446 //  (within module) calls are supported at the moment.
3447 //  To keep the stack aligned according to platform abi the function
3448 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3449 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3450 //  If a tail called function callee has more arguments than the caller the
3451 //  caller needs to make sure that there is room to move the RETADDR to. This is
3452 //  achieved by reserving an area the size of the argument delta right after the
3453 //  original RETADDR, but before the saved framepointer or the spilled registers
3454 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3455 //  stack layout:
3456 //    arg1
3457 //    arg2
3458 //    RETADDR
3459 //    [ new RETADDR
3460 //      move area ]
3461 //    (possible EBP)
3462 //    ESI
3463 //    EDI
3464 //    local1 ..
3465
3466 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3467 /// requirement.
3468 unsigned
3469 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3470                                                SelectionDAG& DAG) const {
3471   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3472   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3473   unsigned StackAlignment = TFI.getStackAlignment();
3474   uint64_t AlignMask = StackAlignment - 1;
3475   int64_t Offset = StackSize;
3476   unsigned SlotSize = RegInfo->getSlotSize();
3477   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3478     // Number smaller than 12 so just add the difference.
3479     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3480   } else {
3481     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3482     Offset = ((~AlignMask) & Offset) + StackAlignment +
3483       (StackAlignment-SlotSize);
3484   }
3485   return Offset;
3486 }
3487
3488 /// Return true if the given stack call argument is already available in the
3489 /// same position (relatively) of the caller's incoming argument stack.
3490 static
3491 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3492                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3493                          const X86InstrInfo *TII) {
3494   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3495   int FI = INT_MAX;
3496   if (Arg.getOpcode() == ISD::CopyFromReg) {
3497     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3498     if (!TargetRegisterInfo::isVirtualRegister(VR))
3499       return false;
3500     MachineInstr *Def = MRI->getVRegDef(VR);
3501     if (!Def)
3502       return false;
3503     if (!Flags.isByVal()) {
3504       if (!TII->isLoadFromStackSlot(Def, FI))
3505         return false;
3506     } else {
3507       unsigned Opcode = Def->getOpcode();
3508       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3509            Opcode == X86::LEA64_32r) &&
3510           Def->getOperand(1).isFI()) {
3511         FI = Def->getOperand(1).getIndex();
3512         Bytes = Flags.getByValSize();
3513       } else
3514         return false;
3515     }
3516   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3517     if (Flags.isByVal())
3518       // ByVal argument is passed in as a pointer but it's now being
3519       // dereferenced. e.g.
3520       // define @foo(%struct.X* %A) {
3521       //   tail call @bar(%struct.X* byval %A)
3522       // }
3523       return false;
3524     SDValue Ptr = Ld->getBasePtr();
3525     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3526     if (!FINode)
3527       return false;
3528     FI = FINode->getIndex();
3529   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3530     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3531     FI = FINode->getIndex();
3532     Bytes = Flags.getByValSize();
3533   } else
3534     return false;
3535
3536   assert(FI != INT_MAX);
3537   if (!MFI->isFixedObjectIndex(FI))
3538     return false;
3539   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3540 }
3541
3542 /// Check whether the call is eligible for tail call optimization. Targets
3543 /// that want to do tail call optimization should implement this function.
3544 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3545     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3546     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3547     const SmallVectorImpl<ISD::OutputArg> &Outs,
3548     const SmallVectorImpl<SDValue> &OutVals,
3549     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3550   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3551     return false;
3552
3553   // If -tailcallopt is specified, make fastcc functions tail-callable.
3554   const MachineFunction &MF = DAG.getMachineFunction();
3555   const Function *CallerF = MF.getFunction();
3556
3557   // If the function return type is x86_fp80 and the callee return type is not,
3558   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3559   // perform a tailcall optimization here.
3560   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3561     return false;
3562
3563   CallingConv::ID CallerCC = CallerF->getCallingConv();
3564   bool CCMatch = CallerCC == CalleeCC;
3565   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3566   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3567
3568   // Win64 functions have extra shadow space for argument homing. Don't do the
3569   // sibcall if the caller and callee have mismatched expectations for this
3570   // space.
3571   if (IsCalleeWin64 != IsCallerWin64)
3572     return false;
3573
3574   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3575     if (IsTailCallConvention(CalleeCC) && CCMatch)
3576       return true;
3577     return false;
3578   }
3579
3580   // Look for obvious safe cases to perform tail call optimization that do not
3581   // require ABI changes. This is what gcc calls sibcall.
3582
3583   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3584   // emit a special epilogue.
3585   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3586   if (RegInfo->needsStackRealignment(MF))
3587     return false;
3588
3589   // Also avoid sibcall optimization if either caller or callee uses struct
3590   // return semantics.
3591   if (isCalleeStructRet || isCallerStructRet)
3592     return false;
3593
3594   // An stdcall/thiscall caller is expected to clean up its arguments; the
3595   // callee isn't going to do that.
3596   // FIXME: this is more restrictive than needed. We could produce a tailcall
3597   // when the stack adjustment matches. For example, with a thiscall that takes
3598   // only one argument.
3599   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3600                    CallerCC == CallingConv::X86_ThisCall))
3601     return false;
3602
3603   // Do not sibcall optimize vararg calls unless all arguments are passed via
3604   // registers.
3605   if (isVarArg && !Outs.empty()) {
3606
3607     // Optimizing for varargs on Win64 is unlikely to be safe without
3608     // additional testing.
3609     if (IsCalleeWin64 || IsCallerWin64)
3610       return false;
3611
3612     SmallVector<CCValAssign, 16> ArgLocs;
3613     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3614                    *DAG.getContext());
3615
3616     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3617     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3618       if (!ArgLocs[i].isRegLoc())
3619         return false;
3620   }
3621
3622   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3623   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3624   // this into a sibcall.
3625   bool Unused = false;
3626   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3627     if (!Ins[i].Used) {
3628       Unused = true;
3629       break;
3630     }
3631   }
3632   if (Unused) {
3633     SmallVector<CCValAssign, 16> RVLocs;
3634     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3635                    *DAG.getContext());
3636     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3637     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3638       CCValAssign &VA = RVLocs[i];
3639       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3640         return false;
3641     }
3642   }
3643
3644   // If the calling conventions do not match, then we'd better make sure the
3645   // results are returned in the same way as what the caller expects.
3646   if (!CCMatch) {
3647     SmallVector<CCValAssign, 16> RVLocs1;
3648     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3649                     *DAG.getContext());
3650     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3651
3652     SmallVector<CCValAssign, 16> RVLocs2;
3653     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3654                     *DAG.getContext());
3655     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3656
3657     if (RVLocs1.size() != RVLocs2.size())
3658       return false;
3659     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3660       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3661         return false;
3662       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3663         return false;
3664       if (RVLocs1[i].isRegLoc()) {
3665         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3666           return false;
3667       } else {
3668         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3669           return false;
3670       }
3671     }
3672   }
3673
3674   // If the callee takes no arguments then go on to check the results of the
3675   // call.
3676   if (!Outs.empty()) {
3677     // Check if stack adjustment is needed. For now, do not do this if any
3678     // argument is passed on the stack.
3679     SmallVector<CCValAssign, 16> ArgLocs;
3680     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3681                    *DAG.getContext());
3682
3683     // Allocate shadow area for Win64
3684     if (IsCalleeWin64)
3685       CCInfo.AllocateStack(32, 8);
3686
3687     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3688     if (CCInfo.getNextStackOffset()) {
3689       MachineFunction &MF = DAG.getMachineFunction();
3690       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3691         return false;
3692
3693       // Check if the arguments are already laid out in the right way as
3694       // the caller's fixed stack objects.
3695       MachineFrameInfo *MFI = MF.getFrameInfo();
3696       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3697       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3698       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3699         CCValAssign &VA = ArgLocs[i];
3700         SDValue Arg = OutVals[i];
3701         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3702         if (VA.getLocInfo() == CCValAssign::Indirect)
3703           return false;
3704         if (!VA.isRegLoc()) {
3705           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3706                                    MFI, MRI, TII))
3707             return false;
3708         }
3709       }
3710     }
3711
3712     // If the tailcall address may be in a register, then make sure it's
3713     // possible to register allocate for it. In 32-bit, the call address can
3714     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3715     // callee-saved registers are restored. These happen to be the same
3716     // registers used to pass 'inreg' arguments so watch out for those.
3717     if (!Subtarget->is64Bit() &&
3718         ((!isa<GlobalAddressSDNode>(Callee) &&
3719           !isa<ExternalSymbolSDNode>(Callee)) ||
3720          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3721       unsigned NumInRegs = 0;
3722       // In PIC we need an extra register to formulate the address computation
3723       // for the callee.
3724       unsigned MaxInRegs =
3725         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3726
3727       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3728         CCValAssign &VA = ArgLocs[i];
3729         if (!VA.isRegLoc())
3730           continue;
3731         unsigned Reg = VA.getLocReg();
3732         switch (Reg) {
3733         default: break;
3734         case X86::EAX: case X86::EDX: case X86::ECX:
3735           if (++NumInRegs == MaxInRegs)
3736             return false;
3737           break;
3738         }
3739       }
3740     }
3741   }
3742
3743   return true;
3744 }
3745
3746 FastISel *
3747 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3748                                   const TargetLibraryInfo *libInfo) const {
3749   return X86::createFastISel(funcInfo, libInfo);
3750 }
3751
3752 //===----------------------------------------------------------------------===//
3753 //                           Other Lowering Hooks
3754 //===----------------------------------------------------------------------===//
3755
3756 static bool MayFoldLoad(SDValue Op) {
3757   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3758 }
3759
3760 static bool MayFoldIntoStore(SDValue Op) {
3761   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3762 }
3763
3764 static bool isTargetShuffle(unsigned Opcode) {
3765   switch(Opcode) {
3766   default: return false;
3767   case X86ISD::BLENDI:
3768   case X86ISD::PSHUFB:
3769   case X86ISD::PSHUFD:
3770   case X86ISD::PSHUFHW:
3771   case X86ISD::PSHUFLW:
3772   case X86ISD::SHUFP:
3773   case X86ISD::PALIGNR:
3774   case X86ISD::MOVLHPS:
3775   case X86ISD::MOVLHPD:
3776   case X86ISD::MOVHLPS:
3777   case X86ISD::MOVLPS:
3778   case X86ISD::MOVLPD:
3779   case X86ISD::MOVSHDUP:
3780   case X86ISD::MOVSLDUP:
3781   case X86ISD::MOVDDUP:
3782   case X86ISD::MOVSS:
3783   case X86ISD::MOVSD:
3784   case X86ISD::UNPCKL:
3785   case X86ISD::UNPCKH:
3786   case X86ISD::VPERMILPI:
3787   case X86ISD::VPERM2X128:
3788   case X86ISD::VPERMI:
3789   case X86ISD::VPERMV:
3790   case X86ISD::VPERMV3:
3791     return true;
3792   }
3793 }
3794
3795 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3796                                     SDValue V1, unsigned TargetMask,
3797                                     SelectionDAG &DAG) {
3798   switch(Opc) {
3799   default: llvm_unreachable("Unknown x86 shuffle node");
3800   case X86ISD::PSHUFD:
3801   case X86ISD::PSHUFHW:
3802   case X86ISD::PSHUFLW:
3803   case X86ISD::VPERMILPI:
3804   case X86ISD::VPERMI:
3805     return DAG.getNode(Opc, dl, VT, V1,
3806                        DAG.getConstant(TargetMask, dl, MVT::i8));
3807   }
3808 }
3809
3810 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3811                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3812   switch(Opc) {
3813   default: llvm_unreachable("Unknown x86 shuffle node");
3814   case X86ISD::MOVLHPS:
3815   case X86ISD::MOVLHPD:
3816   case X86ISD::MOVHLPS:
3817   case X86ISD::MOVLPS:
3818   case X86ISD::MOVLPD:
3819   case X86ISD::MOVSS:
3820   case X86ISD::MOVSD:
3821   case X86ISD::UNPCKL:
3822   case X86ISD::UNPCKH:
3823     return DAG.getNode(Opc, dl, VT, V1, V2);
3824   }
3825 }
3826
3827 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3828   MachineFunction &MF = DAG.getMachineFunction();
3829   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3830   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3831   int ReturnAddrIndex = FuncInfo->getRAIndex();
3832
3833   if (ReturnAddrIndex == 0) {
3834     // Set up a frame object for the return address.
3835     unsigned SlotSize = RegInfo->getSlotSize();
3836     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3837                                                            -(int64_t)SlotSize,
3838                                                            false);
3839     FuncInfo->setRAIndex(ReturnAddrIndex);
3840   }
3841
3842   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3843 }
3844
3845 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3846                                        bool hasSymbolicDisplacement) {
3847   // Offset should fit into 32 bit immediate field.
3848   if (!isInt<32>(Offset))
3849     return false;
3850
3851   // If we don't have a symbolic displacement - we don't have any extra
3852   // restrictions.
3853   if (!hasSymbolicDisplacement)
3854     return true;
3855
3856   // FIXME: Some tweaks might be needed for medium code model.
3857   if (M != CodeModel::Small && M != CodeModel::Kernel)
3858     return false;
3859
3860   // For small code model we assume that latest object is 16MB before end of 31
3861   // bits boundary. We may also accept pretty large negative constants knowing
3862   // that all objects are in the positive half of address space.
3863   if (M == CodeModel::Small && Offset < 16*1024*1024)
3864     return true;
3865
3866   // For kernel code model we know that all object resist in the negative half
3867   // of 32bits address space. We may not accept negative offsets, since they may
3868   // be just off and we may accept pretty large positive ones.
3869   if (M == CodeModel::Kernel && Offset >= 0)
3870     return true;
3871
3872   return false;
3873 }
3874
3875 /// Determines whether the callee is required to pop its own arguments.
3876 /// Callee pop is necessary to support tail calls.
3877 bool X86::isCalleePop(CallingConv::ID CallingConv,
3878                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3879   switch (CallingConv) {
3880   default:
3881     return false;
3882   case CallingConv::X86_StdCall:
3883   case CallingConv::X86_FastCall:
3884   case CallingConv::X86_ThisCall:
3885     return !is64Bit;
3886   case CallingConv::Fast:
3887   case CallingConv::GHC:
3888   case CallingConv::HiPE:
3889     if (IsVarArg)
3890       return false;
3891     return TailCallOpt;
3892   }
3893 }
3894
3895 /// \brief Return true if the condition is an unsigned comparison operation.
3896 static bool isX86CCUnsigned(unsigned X86CC) {
3897   switch (X86CC) {
3898   default: llvm_unreachable("Invalid integer condition!");
3899   case X86::COND_E:     return true;
3900   case X86::COND_G:     return false;
3901   case X86::COND_GE:    return false;
3902   case X86::COND_L:     return false;
3903   case X86::COND_LE:    return false;
3904   case X86::COND_NE:    return true;
3905   case X86::COND_B:     return true;
3906   case X86::COND_A:     return true;
3907   case X86::COND_BE:    return true;
3908   case X86::COND_AE:    return true;
3909   }
3910   llvm_unreachable("covered switch fell through?!");
3911 }
3912
3913 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3914 /// condition code, returning the condition code and the LHS/RHS of the
3915 /// comparison to make.
3916 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3917                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3918   if (!isFP) {
3919     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3920       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3921         // X > -1   -> X == 0, jump !sign.
3922         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3923         return X86::COND_NS;
3924       }
3925       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3926         // X < 0   -> X == 0, jump on sign.
3927         return X86::COND_S;
3928       }
3929       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3930         // X < 1   -> X <= 0
3931         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3932         return X86::COND_LE;
3933       }
3934     }
3935
3936     switch (SetCCOpcode) {
3937     default: llvm_unreachable("Invalid integer condition!");
3938     case ISD::SETEQ:  return X86::COND_E;
3939     case ISD::SETGT:  return X86::COND_G;
3940     case ISD::SETGE:  return X86::COND_GE;
3941     case ISD::SETLT:  return X86::COND_L;
3942     case ISD::SETLE:  return X86::COND_LE;
3943     case ISD::SETNE:  return X86::COND_NE;
3944     case ISD::SETULT: return X86::COND_B;
3945     case ISD::SETUGT: return X86::COND_A;
3946     case ISD::SETULE: return X86::COND_BE;
3947     case ISD::SETUGE: return X86::COND_AE;
3948     }
3949   }
3950
3951   // First determine if it is required or is profitable to flip the operands.
3952
3953   // If LHS is a foldable load, but RHS is not, flip the condition.
3954   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3955       !ISD::isNON_EXTLoad(RHS.getNode())) {
3956     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3957     std::swap(LHS, RHS);
3958   }
3959
3960   switch (SetCCOpcode) {
3961   default: break;
3962   case ISD::SETOLT:
3963   case ISD::SETOLE:
3964   case ISD::SETUGT:
3965   case ISD::SETUGE:
3966     std::swap(LHS, RHS);
3967     break;
3968   }
3969
3970   // On a floating point condition, the flags are set as follows:
3971   // ZF  PF  CF   op
3972   //  0 | 0 | 0 | X > Y
3973   //  0 | 0 | 1 | X < Y
3974   //  1 | 0 | 0 | X == Y
3975   //  1 | 1 | 1 | unordered
3976   switch (SetCCOpcode) {
3977   default: llvm_unreachable("Condcode should be pre-legalized away");
3978   case ISD::SETUEQ:
3979   case ISD::SETEQ:   return X86::COND_E;
3980   case ISD::SETOLT:              // flipped
3981   case ISD::SETOGT:
3982   case ISD::SETGT:   return X86::COND_A;
3983   case ISD::SETOLE:              // flipped
3984   case ISD::SETOGE:
3985   case ISD::SETGE:   return X86::COND_AE;
3986   case ISD::SETUGT:              // flipped
3987   case ISD::SETULT:
3988   case ISD::SETLT:   return X86::COND_B;
3989   case ISD::SETUGE:              // flipped
3990   case ISD::SETULE:
3991   case ISD::SETLE:   return X86::COND_BE;
3992   case ISD::SETONE:
3993   case ISD::SETNE:   return X86::COND_NE;
3994   case ISD::SETUO:   return X86::COND_P;
3995   case ISD::SETO:    return X86::COND_NP;
3996   case ISD::SETOEQ:
3997   case ISD::SETUNE:  return X86::COND_INVALID;
3998   }
3999 }
4000
4001 /// Is there a floating point cmov for the specific X86 condition code?
4002 /// Current x86 isa includes the following FP cmov instructions:
4003 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4004 static bool hasFPCMov(unsigned X86CC) {
4005   switch (X86CC) {
4006   default:
4007     return false;
4008   case X86::COND_B:
4009   case X86::COND_BE:
4010   case X86::COND_E:
4011   case X86::COND_P:
4012   case X86::COND_A:
4013   case X86::COND_AE:
4014   case X86::COND_NE:
4015   case X86::COND_NP:
4016     return true;
4017   }
4018 }
4019
4020 /// Returns true if the target can instruction select the
4021 /// specified FP immediate natively. If false, the legalizer will
4022 /// materialize the FP immediate as a load from a constant pool.
4023 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4024   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4025     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4026       return true;
4027   }
4028   return false;
4029 }
4030
4031 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4032                                               ISD::LoadExtType ExtTy,
4033                                               EVT NewVT) const {
4034   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4035   // relocation target a movq or addq instruction: don't let the load shrink.
4036   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4037   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4038     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4039       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4040   return true;
4041 }
4042
4043 /// \brief Returns true if it is beneficial to convert a load of a constant
4044 /// to just the constant itself.
4045 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4046                                                           Type *Ty) const {
4047   assert(Ty->isIntegerTy());
4048
4049   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4050   if (BitSize == 0 || BitSize > 64)
4051     return false;
4052   return true;
4053 }
4054
4055 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4056                                                 unsigned Index) const {
4057   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4058     return false;
4059
4060   return (Index == 0 || Index == ResVT.getVectorNumElements());
4061 }
4062
4063 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4064   // Speculate cttz only if we can directly use TZCNT.
4065   return Subtarget->hasBMI();
4066 }
4067
4068 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4069   // Speculate ctlz only if we can directly use LZCNT.
4070   return Subtarget->hasLZCNT();
4071 }
4072
4073 /// Return true if every element in Mask, beginning
4074 /// from position Pos and ending in Pos+Size is undef.
4075 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4076   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4077     if (0 <= Mask[i])
4078       return false;
4079   return true;
4080 }
4081
4082 /// Return true if Val is undef or if its value falls within the
4083 /// specified range (L, H].
4084 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4085   return (Val < 0) || (Val >= Low && Val < Hi);
4086 }
4087
4088 /// Val is either less than zero (undef) or equal to the specified value.
4089 static bool isUndefOrEqual(int Val, int CmpVal) {
4090   return (Val < 0 || Val == CmpVal);
4091 }
4092
4093 /// Return true if every element in Mask, beginning
4094 /// from position Pos and ending in Pos+Size, falls within the specified
4095 /// sequential range (Low, Low+Size]. or is undef.
4096 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4097                                        unsigned Pos, unsigned Size, int Low) {
4098   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4099     if (!isUndefOrEqual(Mask[i], Low))
4100       return false;
4101   return true;
4102 }
4103
4104 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4105 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4106 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4107   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4108   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4109     return false;
4110
4111   // The index should be aligned on a vecWidth-bit boundary.
4112   uint64_t Index =
4113     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4114
4115   MVT VT = N->getSimpleValueType(0);
4116   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4117   bool Result = (Index * ElSize) % vecWidth == 0;
4118
4119   return Result;
4120 }
4121
4122 /// Return true if the specified INSERT_SUBVECTOR
4123 /// operand specifies a subvector insert that is suitable for input to
4124 /// insertion of 128 or 256-bit subvectors
4125 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4126   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4127   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4128     return false;
4129   // The index should be aligned on a vecWidth-bit boundary.
4130   uint64_t Index =
4131     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4132
4133   MVT VT = N->getSimpleValueType(0);
4134   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4135   bool Result = (Index * ElSize) % vecWidth == 0;
4136
4137   return Result;
4138 }
4139
4140 bool X86::isVINSERT128Index(SDNode *N) {
4141   return isVINSERTIndex(N, 128);
4142 }
4143
4144 bool X86::isVINSERT256Index(SDNode *N) {
4145   return isVINSERTIndex(N, 256);
4146 }
4147
4148 bool X86::isVEXTRACT128Index(SDNode *N) {
4149   return isVEXTRACTIndex(N, 128);
4150 }
4151
4152 bool X86::isVEXTRACT256Index(SDNode *N) {
4153   return isVEXTRACTIndex(N, 256);
4154 }
4155
4156 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4157   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4158   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4159     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4160
4161   uint64_t Index =
4162     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4163
4164   MVT VecVT = N->getOperand(0).getSimpleValueType();
4165   MVT ElVT = VecVT.getVectorElementType();
4166
4167   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4168   return Index / NumElemsPerChunk;
4169 }
4170
4171 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4172   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4173   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4174     llvm_unreachable("Illegal insert subvector for VINSERT");
4175
4176   uint64_t Index =
4177     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4178
4179   MVT VecVT = N->getSimpleValueType(0);
4180   MVT ElVT = VecVT.getVectorElementType();
4181
4182   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4183   return Index / NumElemsPerChunk;
4184 }
4185
4186 /// Return the appropriate immediate to extract the specified
4187 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4188 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4189   return getExtractVEXTRACTImmediate(N, 128);
4190 }
4191
4192 /// Return the appropriate immediate to extract the specified
4193 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4194 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4195   return getExtractVEXTRACTImmediate(N, 256);
4196 }
4197
4198 /// Return the appropriate immediate to insert at the specified
4199 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4200 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4201   return getInsertVINSERTImmediate(N, 128);
4202 }
4203
4204 /// Return the appropriate immediate to insert at the specified
4205 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4206 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4207   return getInsertVINSERTImmediate(N, 256);
4208 }
4209
4210 /// Returns true if Elt is a constant integer zero
4211 static bool isZero(SDValue V) {
4212   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4213   return C && C->isNullValue();
4214 }
4215
4216 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4217 bool X86::isZeroNode(SDValue Elt) {
4218   if (isZero(Elt))
4219     return true;
4220   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4221     return CFP->getValueAPF().isPosZero();
4222   return false;
4223 }
4224
4225 /// Returns a vector of specified type with all zero elements.
4226 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4227                              SelectionDAG &DAG, SDLoc dl) {
4228   assert(VT.isVector() && "Expected a vector type");
4229
4230   // Always build SSE zero vectors as <4 x i32> bitcasted
4231   // to their dest type. This ensures they get CSE'd.
4232   SDValue Vec;
4233   if (VT.is128BitVector()) {  // SSE
4234     if (Subtarget->hasSSE2()) {  // SSE2
4235       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4236       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4237     } else { // SSE1
4238       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4239       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4240     }
4241   } else if (VT.is256BitVector()) { // AVX
4242     if (Subtarget->hasInt256()) { // AVX2
4243       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4244       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4245       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4246     } else {
4247       // 256-bit logic and arithmetic instructions in AVX are all
4248       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4249       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4250       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4251       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4252     }
4253   } else if (VT.is512BitVector()) { // AVX-512
4254       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4255       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4256                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4257       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4258   } else if (VT.getScalarType() == MVT::i1) {
4259
4260     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4261             && "Unexpected vector type");
4262     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4263             && "Unexpected vector type");
4264     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4265     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4266     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4267   } else
4268     llvm_unreachable("Unexpected vector type");
4269
4270   return DAG.getBitcast(VT, Vec);
4271 }
4272
4273 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4274                                 SelectionDAG &DAG, SDLoc dl,
4275                                 unsigned vectorWidth) {
4276   assert((vectorWidth == 128 || vectorWidth == 256) &&
4277          "Unsupported vector width");
4278   EVT VT = Vec.getValueType();
4279   EVT ElVT = VT.getVectorElementType();
4280   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4281   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4282                                   VT.getVectorNumElements()/Factor);
4283
4284   // Extract from UNDEF is UNDEF.
4285   if (Vec.getOpcode() == ISD::UNDEF)
4286     return DAG.getUNDEF(ResultVT);
4287
4288   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4289   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4290
4291   // This is the index of the first element of the vectorWidth-bit chunk
4292   // we want.
4293   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4294                                * ElemsPerChunk);
4295
4296   // If the input is a buildvector just emit a smaller one.
4297   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4298     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4299                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4300                                     ElemsPerChunk));
4301
4302   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4303   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4304 }
4305
4306 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4307 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4308 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4309 /// instructions or a simple subregister reference. Idx is an index in the
4310 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4311 /// lowering EXTRACT_VECTOR_ELT operations easier.
4312 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4313                                    SelectionDAG &DAG, SDLoc dl) {
4314   assert((Vec.getValueType().is256BitVector() ||
4315           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4316   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4317 }
4318
4319 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4320 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4321                                    SelectionDAG &DAG, SDLoc dl) {
4322   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4323   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4324 }
4325
4326 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4327                                unsigned IdxVal, SelectionDAG &DAG,
4328                                SDLoc dl, unsigned vectorWidth) {
4329   assert((vectorWidth == 128 || vectorWidth == 256) &&
4330          "Unsupported vector width");
4331   // Inserting UNDEF is Result
4332   if (Vec.getOpcode() == ISD::UNDEF)
4333     return Result;
4334   EVT VT = Vec.getValueType();
4335   EVT ElVT = VT.getVectorElementType();
4336   EVT ResultVT = Result.getValueType();
4337
4338   // Insert the relevant vectorWidth bits.
4339   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4340
4341   // This is the index of the first element of the vectorWidth-bit chunk
4342   // we want.
4343   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4344                                * ElemsPerChunk);
4345
4346   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4347   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4348 }
4349
4350 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4351 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4352 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4353 /// simple superregister reference.  Idx is an index in the 128 bits
4354 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4355 /// lowering INSERT_VECTOR_ELT operations easier.
4356 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4357                                   SelectionDAG &DAG, SDLoc dl) {
4358   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4359
4360   // For insertion into the zero index (low half) of a 256-bit vector, it is
4361   // more efficient to generate a blend with immediate instead of an insert*128.
4362   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4363   // extend the subvector to the size of the result vector. Make sure that
4364   // we are not recursing on that node by checking for undef here.
4365   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4366       Result.getOpcode() != ISD::UNDEF) {
4367     EVT ResultVT = Result.getValueType();
4368     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4369     SDValue Undef = DAG.getUNDEF(ResultVT);
4370     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4371                                  Vec, ZeroIndex);
4372
4373     // The blend instruction, and therefore its mask, depend on the data type.
4374     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4375     if (ScalarType.isFloatingPoint()) {
4376       // Choose either vblendps (float) or vblendpd (double).
4377       unsigned ScalarSize = ScalarType.getSizeInBits();
4378       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4379       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4380       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4381       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4382     }
4383
4384     const X86Subtarget &Subtarget =
4385     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4386
4387     // AVX2 is needed for 256-bit integer blend support.
4388     // Integers must be cast to 32-bit because there is only vpblendd;
4389     // vpblendw can't be used for this because it has a handicapped mask.
4390
4391     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4392     // is still more efficient than using the wrong domain vinsertf128 that
4393     // will be created by InsertSubVector().
4394     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4395
4396     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4397     Vec256 = DAG.getBitcast(CastVT, Vec256);
4398     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4399     return DAG.getBitcast(ResultVT, Vec256);
4400   }
4401
4402   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4403 }
4404
4405 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4406                                   SelectionDAG &DAG, SDLoc dl) {
4407   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4408   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4409 }
4410
4411 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4412 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4413 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4414 /// large BUILD_VECTORS.
4415 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4416                                    unsigned NumElems, SelectionDAG &DAG,
4417                                    SDLoc dl) {
4418   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4419   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4420 }
4421
4422 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4423                                    unsigned NumElems, SelectionDAG &DAG,
4424                                    SDLoc dl) {
4425   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4426   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4427 }
4428
4429 /// Returns a vector of specified type with all bits set.
4430 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4431 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4432 /// Then bitcast to their original type, ensuring they get CSE'd.
4433 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4434                              SelectionDAG &DAG, SDLoc dl) {
4435   assert(VT.isVector() && "Expected a vector type");
4436
4437   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4438   SDValue Vec;
4439   if (VT.is512BitVector()) {
4440     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4441                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4442     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4443   } else if (VT.is256BitVector()) {
4444     if (Subtarget->hasInt256()) { // AVX2
4445       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4446       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4447     } else { // AVX
4448       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4449       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4450     }
4451   } else if (VT.is128BitVector()) {
4452     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4453   } else
4454     llvm_unreachable("Unexpected vector type");
4455
4456   return DAG.getBitcast(VT, Vec);
4457 }
4458
4459 /// Returns a vector_shuffle node for an unpackl operation.
4460 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4461                           SDValue V2) {
4462   unsigned NumElems = VT.getVectorNumElements();
4463   SmallVector<int, 8> Mask;
4464   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4465     Mask.push_back(i);
4466     Mask.push_back(i + NumElems);
4467   }
4468   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4469 }
4470
4471 /// Returns a vector_shuffle node for an unpackh operation.
4472 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4473                           SDValue V2) {
4474   unsigned NumElems = VT.getVectorNumElements();
4475   SmallVector<int, 8> Mask;
4476   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4477     Mask.push_back(i + Half);
4478     Mask.push_back(i + NumElems + Half);
4479   }
4480   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4481 }
4482
4483 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4484 /// This produces a shuffle where the low element of V2 is swizzled into the
4485 /// zero/undef vector, landing at element Idx.
4486 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4487 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4488                                            bool IsZero,
4489                                            const X86Subtarget *Subtarget,
4490                                            SelectionDAG &DAG) {
4491   MVT VT = V2.getSimpleValueType();
4492   SDValue V1 = IsZero
4493     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4494   unsigned NumElems = VT.getVectorNumElements();
4495   SmallVector<int, 16> MaskVec;
4496   for (unsigned i = 0; i != NumElems; ++i)
4497     // If this is the insertion idx, put the low elt of V2 here.
4498     MaskVec.push_back(i == Idx ? NumElems : i);
4499   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4500 }
4501
4502 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4503 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4504 /// uses one source. Note that this will set IsUnary for shuffles which use a
4505 /// single input multiple times, and in those cases it will
4506 /// adjust the mask to only have indices within that single input.
4507 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4508 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4509                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4510   unsigned NumElems = VT.getVectorNumElements();
4511   SDValue ImmN;
4512
4513   IsUnary = false;
4514   bool IsFakeUnary = false;
4515   switch(N->getOpcode()) {
4516   case X86ISD::BLENDI:
4517     ImmN = N->getOperand(N->getNumOperands()-1);
4518     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519     break;
4520   case X86ISD::SHUFP:
4521     ImmN = N->getOperand(N->getNumOperands()-1);
4522     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4523     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4524     break;
4525   case X86ISD::UNPCKH:
4526     DecodeUNPCKHMask(VT, Mask);
4527     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4528     break;
4529   case X86ISD::UNPCKL:
4530     DecodeUNPCKLMask(VT, Mask);
4531     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4532     break;
4533   case X86ISD::MOVHLPS:
4534     DecodeMOVHLPSMask(NumElems, Mask);
4535     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4536     break;
4537   case X86ISD::MOVLHPS:
4538     DecodeMOVLHPSMask(NumElems, Mask);
4539     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4540     break;
4541   case X86ISD::PALIGNR:
4542     ImmN = N->getOperand(N->getNumOperands()-1);
4543     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4544     break;
4545   case X86ISD::PSHUFD:
4546   case X86ISD::VPERMILPI:
4547     ImmN = N->getOperand(N->getNumOperands()-1);
4548     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4549     IsUnary = true;
4550     break;
4551   case X86ISD::PSHUFHW:
4552     ImmN = N->getOperand(N->getNumOperands()-1);
4553     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4554     IsUnary = true;
4555     break;
4556   case X86ISD::PSHUFLW:
4557     ImmN = N->getOperand(N->getNumOperands()-1);
4558     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4559     IsUnary = true;
4560     break;
4561   case X86ISD::PSHUFB: {
4562     IsUnary = true;
4563     SDValue MaskNode = N->getOperand(1);
4564     while (MaskNode->getOpcode() == ISD::BITCAST)
4565       MaskNode = MaskNode->getOperand(0);
4566
4567     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4568       // If we have a build-vector, then things are easy.
4569       EVT VT = MaskNode.getValueType();
4570       assert(VT.isVector() &&
4571              "Can't produce a non-vector with a build_vector!");
4572       if (!VT.isInteger())
4573         return false;
4574
4575       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4576
4577       SmallVector<uint64_t, 32> RawMask;
4578       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4579         SDValue Op = MaskNode->getOperand(i);
4580         if (Op->getOpcode() == ISD::UNDEF) {
4581           RawMask.push_back((uint64_t)SM_SentinelUndef);
4582           continue;
4583         }
4584         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4585         if (!CN)
4586           return false;
4587         APInt MaskElement = CN->getAPIntValue();
4588
4589         // We now have to decode the element which could be any integer size and
4590         // extract each byte of it.
4591         for (int j = 0; j < NumBytesPerElement; ++j) {
4592           // Note that this is x86 and so always little endian: the low byte is
4593           // the first byte of the mask.
4594           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4595           MaskElement = MaskElement.lshr(8);
4596         }
4597       }
4598       DecodePSHUFBMask(RawMask, Mask);
4599       break;
4600     }
4601
4602     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4603     if (!MaskLoad)
4604       return false;
4605
4606     SDValue Ptr = MaskLoad->getBasePtr();
4607     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4608         Ptr->getOpcode() == X86ISD::WrapperRIP)
4609       Ptr = Ptr->getOperand(0);
4610
4611     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4612     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4613       return false;
4614
4615     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4616       DecodePSHUFBMask(C, Mask);
4617       if (Mask.empty())
4618         return false;
4619       break;
4620     }
4621
4622     return false;
4623   }
4624   case X86ISD::VPERMI:
4625     ImmN = N->getOperand(N->getNumOperands()-1);
4626     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4627     IsUnary = true;
4628     break;
4629   case X86ISD::MOVSS:
4630   case X86ISD::MOVSD:
4631     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4632     break;
4633   case X86ISD::VPERM2X128:
4634     ImmN = N->getOperand(N->getNumOperands()-1);
4635     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4636     if (Mask.empty()) return false;
4637     // Mask only contains negative index if an element is zero.
4638     if (std::any_of(Mask.begin(), Mask.end(),
4639                     [](int M){ return M == SM_SentinelZero; }))
4640       return false;
4641     break;
4642   case X86ISD::MOVSLDUP:
4643     DecodeMOVSLDUPMask(VT, Mask);
4644     IsUnary = true;
4645     break;
4646   case X86ISD::MOVSHDUP:
4647     DecodeMOVSHDUPMask(VT, Mask);
4648     IsUnary = true;
4649     break;
4650   case X86ISD::MOVDDUP:
4651     DecodeMOVDDUPMask(VT, Mask);
4652     IsUnary = true;
4653     break;
4654   case X86ISD::MOVLHPD:
4655   case X86ISD::MOVLPD:
4656   case X86ISD::MOVLPS:
4657     // Not yet implemented
4658     return false;
4659   case X86ISD::VPERMV: {
4660     IsUnary = true;
4661     SDValue MaskNode = N->getOperand(0);
4662     while (MaskNode->getOpcode() == ISD::BITCAST)
4663       MaskNode = MaskNode->getOperand(0);
4664
4665     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4666     SmallVector<uint64_t, 32> RawMask;
4667     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4668       // If we have a build-vector, then things are easy.
4669       assert(MaskNode.getValueType().isInteger() &&
4670              MaskNode.getValueType().getVectorNumElements() ==
4671              VT.getVectorNumElements());
4672
4673       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4674         SDValue Op = MaskNode->getOperand(i);
4675         if (Op->getOpcode() == ISD::UNDEF)
4676           RawMask.push_back((uint64_t)SM_SentinelUndef);
4677         else if (isa<ConstantSDNode>(Op)) {
4678           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4679           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4680         } else
4681           return false;
4682       }
4683       DecodeVPERMVMask(RawMask, Mask);
4684       break;
4685     }
4686     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4687       unsigned NumEltsInMask = MaskNode->getNumOperands();
4688       MaskNode = MaskNode->getOperand(0);
4689       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4690       if (CN) {
4691         APInt MaskEltValue = CN->getAPIntValue();
4692         for (unsigned i = 0; i < NumEltsInMask; ++i)
4693           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4694         DecodeVPERMVMask(RawMask, Mask);
4695         break;
4696       }
4697       // It may be a scalar load
4698     }
4699
4700     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4701     if (!MaskLoad)
4702       return false;
4703
4704     SDValue Ptr = MaskLoad->getBasePtr();
4705     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4706         Ptr->getOpcode() == X86ISD::WrapperRIP)
4707       Ptr = Ptr->getOperand(0);
4708
4709     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4710     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4711       return false;
4712
4713     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4714     if (C) {
4715       DecodeVPERMVMask(C, VT, Mask);
4716       if (Mask.empty())
4717         return false;
4718       break;
4719     }
4720     return false;
4721   }
4722   case X86ISD::VPERMV3: {
4723     IsUnary = false;
4724     SDValue MaskNode = N->getOperand(1);
4725     while (MaskNode->getOpcode() == ISD::BITCAST)
4726       MaskNode = MaskNode->getOperand(1);
4727
4728     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4729       // If we have a build-vector, then things are easy.
4730       assert(MaskNode.getValueType().isInteger() &&
4731              MaskNode.getValueType().getVectorNumElements() ==
4732              VT.getVectorNumElements());
4733
4734       SmallVector<uint64_t, 32> RawMask;
4735       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4736
4737       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4738         SDValue Op = MaskNode->getOperand(i);
4739         if (Op->getOpcode() == ISD::UNDEF)
4740           RawMask.push_back((uint64_t)SM_SentinelUndef);
4741         else {
4742           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4743           if (!CN)
4744             return false;
4745           APInt MaskElement = CN->getAPIntValue();
4746           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4747         }
4748       }
4749       DecodeVPERMV3Mask(RawMask, Mask);
4750       break;
4751     }
4752
4753     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4754     if (!MaskLoad)
4755       return false;
4756
4757     SDValue Ptr = MaskLoad->getBasePtr();
4758     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4759         Ptr->getOpcode() == X86ISD::WrapperRIP)
4760       Ptr = Ptr->getOperand(0);
4761
4762     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4763     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4764       return false;
4765
4766     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4767     if (C) {
4768       DecodeVPERMV3Mask(C, VT, Mask);
4769       if (Mask.empty())
4770         return false;
4771       break;
4772     }
4773     return false;
4774   }
4775   default: llvm_unreachable("unknown target shuffle node");
4776   }
4777
4778   // If we have a fake unary shuffle, the shuffle mask is spread across two
4779   // inputs that are actually the same node. Re-map the mask to always point
4780   // into the first input.
4781   if (IsFakeUnary)
4782     for (int &M : Mask)
4783       if (M >= (int)Mask.size())
4784         M -= Mask.size();
4785
4786   return true;
4787 }
4788
4789 /// Returns the scalar element that will make up the ith
4790 /// element of the result of the vector shuffle.
4791 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4792                                    unsigned Depth) {
4793   if (Depth == 6)
4794     return SDValue();  // Limit search depth.
4795
4796   SDValue V = SDValue(N, 0);
4797   EVT VT = V.getValueType();
4798   unsigned Opcode = V.getOpcode();
4799
4800   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4801   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4802     int Elt = SV->getMaskElt(Index);
4803
4804     if (Elt < 0)
4805       return DAG.getUNDEF(VT.getVectorElementType());
4806
4807     unsigned NumElems = VT.getVectorNumElements();
4808     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4809                                          : SV->getOperand(1);
4810     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4811   }
4812
4813   // Recurse into target specific vector shuffles to find scalars.
4814   if (isTargetShuffle(Opcode)) {
4815     MVT ShufVT = V.getSimpleValueType();
4816     unsigned NumElems = ShufVT.getVectorNumElements();
4817     SmallVector<int, 16> ShuffleMask;
4818     bool IsUnary;
4819
4820     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4821       return SDValue();
4822
4823     int Elt = ShuffleMask[Index];
4824     if (Elt < 0)
4825       return DAG.getUNDEF(ShufVT.getVectorElementType());
4826
4827     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4828                                          : N->getOperand(1);
4829     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4830                                Depth+1);
4831   }
4832
4833   // Actual nodes that may contain scalar elements
4834   if (Opcode == ISD::BITCAST) {
4835     V = V.getOperand(0);
4836     EVT SrcVT = V.getValueType();
4837     unsigned NumElems = VT.getVectorNumElements();
4838
4839     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4840       return SDValue();
4841   }
4842
4843   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4844     return (Index == 0) ? V.getOperand(0)
4845                         : DAG.getUNDEF(VT.getVectorElementType());
4846
4847   if (V.getOpcode() == ISD::BUILD_VECTOR)
4848     return V.getOperand(Index);
4849
4850   return SDValue();
4851 }
4852
4853 /// Custom lower build_vector of v16i8.
4854 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4855                                        unsigned NumNonZero, unsigned NumZero,
4856                                        SelectionDAG &DAG,
4857                                        const X86Subtarget* Subtarget,
4858                                        const TargetLowering &TLI) {
4859   if (NumNonZero > 8)
4860     return SDValue();
4861
4862   SDLoc dl(Op);
4863   SDValue V;
4864   bool First = true;
4865
4866   // SSE4.1 - use PINSRB to insert each byte directly.
4867   if (Subtarget->hasSSE41()) {
4868     for (unsigned i = 0; i < 16; ++i) {
4869       bool isNonZero = (NonZeros & (1 << i)) != 0;
4870       if (isNonZero) {
4871         if (First) {
4872           if (NumZero)
4873             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4874           else
4875             V = DAG.getUNDEF(MVT::v16i8);
4876           First = false;
4877         }
4878         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4879                         MVT::v16i8, V, Op.getOperand(i),
4880                         DAG.getIntPtrConstant(i, dl));
4881       }
4882     }
4883
4884     return V;
4885   }
4886
4887   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4888   for (unsigned i = 0; i < 16; ++i) {
4889     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4890     if (ThisIsNonZero && First) {
4891       if (NumZero)
4892         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4893       else
4894         V = DAG.getUNDEF(MVT::v8i16);
4895       First = false;
4896     }
4897
4898     if ((i & 1) != 0) {
4899       SDValue ThisElt, LastElt;
4900       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4901       if (LastIsNonZero) {
4902         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4903                               MVT::i16, Op.getOperand(i-1));
4904       }
4905       if (ThisIsNonZero) {
4906         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4907         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4908                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4909         if (LastIsNonZero)
4910           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4911       } else
4912         ThisElt = LastElt;
4913
4914       if (ThisElt.getNode())
4915         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4916                         DAG.getIntPtrConstant(i/2, dl));
4917     }
4918   }
4919
4920   return DAG.getBitcast(MVT::v16i8, V);
4921 }
4922
4923 /// Custom lower build_vector of v8i16.
4924 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4925                                      unsigned NumNonZero, unsigned NumZero,
4926                                      SelectionDAG &DAG,
4927                                      const X86Subtarget* Subtarget,
4928                                      const TargetLowering &TLI) {
4929   if (NumNonZero > 4)
4930     return SDValue();
4931
4932   SDLoc dl(Op);
4933   SDValue V;
4934   bool First = true;
4935   for (unsigned i = 0; i < 8; ++i) {
4936     bool isNonZero = (NonZeros & (1 << i)) != 0;
4937     if (isNonZero) {
4938       if (First) {
4939         if (NumZero)
4940           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4941         else
4942           V = DAG.getUNDEF(MVT::v8i16);
4943         First = false;
4944       }
4945       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4946                       MVT::v8i16, V, Op.getOperand(i),
4947                       DAG.getIntPtrConstant(i, dl));
4948     }
4949   }
4950
4951   return V;
4952 }
4953
4954 /// Custom lower build_vector of v4i32 or v4f32.
4955 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4956                                      const X86Subtarget *Subtarget,
4957                                      const TargetLowering &TLI) {
4958   // Find all zeroable elements.
4959   std::bitset<4> Zeroable;
4960   for (int i=0; i < 4; ++i) {
4961     SDValue Elt = Op->getOperand(i);
4962     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4963   }
4964   assert(Zeroable.size() - Zeroable.count() > 1 &&
4965          "We expect at least two non-zero elements!");
4966
4967   // We only know how to deal with build_vector nodes where elements are either
4968   // zeroable or extract_vector_elt with constant index.
4969   SDValue FirstNonZero;
4970   unsigned FirstNonZeroIdx;
4971   for (unsigned i=0; i < 4; ++i) {
4972     if (Zeroable[i])
4973       continue;
4974     SDValue Elt = Op->getOperand(i);
4975     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4976         !isa<ConstantSDNode>(Elt.getOperand(1)))
4977       return SDValue();
4978     // Make sure that this node is extracting from a 128-bit vector.
4979     MVT VT = Elt.getOperand(0).getSimpleValueType();
4980     if (!VT.is128BitVector())
4981       return SDValue();
4982     if (!FirstNonZero.getNode()) {
4983       FirstNonZero = Elt;
4984       FirstNonZeroIdx = i;
4985     }
4986   }
4987
4988   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4989   SDValue V1 = FirstNonZero.getOperand(0);
4990   MVT VT = V1.getSimpleValueType();
4991
4992   // See if this build_vector can be lowered as a blend with zero.
4993   SDValue Elt;
4994   unsigned EltMaskIdx, EltIdx;
4995   int Mask[4];
4996   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4997     if (Zeroable[EltIdx]) {
4998       // The zero vector will be on the right hand side.
4999       Mask[EltIdx] = EltIdx+4;
5000       continue;
5001     }
5002
5003     Elt = Op->getOperand(EltIdx);
5004     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5005     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5006     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5007       break;
5008     Mask[EltIdx] = EltIdx;
5009   }
5010
5011   if (EltIdx == 4) {
5012     // Let the shuffle legalizer deal with blend operations.
5013     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5014     if (V1.getSimpleValueType() != VT)
5015       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5016     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5017   }
5018
5019   // See if we can lower this build_vector to a INSERTPS.
5020   if (!Subtarget->hasSSE41())
5021     return SDValue();
5022
5023   SDValue V2 = Elt.getOperand(0);
5024   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5025     V1 = SDValue();
5026
5027   bool CanFold = true;
5028   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5029     if (Zeroable[i])
5030       continue;
5031
5032     SDValue Current = Op->getOperand(i);
5033     SDValue SrcVector = Current->getOperand(0);
5034     if (!V1.getNode())
5035       V1 = SrcVector;
5036     CanFold = SrcVector == V1 &&
5037       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5038   }
5039
5040   if (!CanFold)
5041     return SDValue();
5042
5043   assert(V1.getNode() && "Expected at least two non-zero elements!");
5044   if (V1.getSimpleValueType() != MVT::v4f32)
5045     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5046   if (V2.getSimpleValueType() != MVT::v4f32)
5047     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5048
5049   // Ok, we can emit an INSERTPS instruction.
5050   unsigned ZMask = Zeroable.to_ulong();
5051
5052   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5053   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5054   SDLoc DL(Op);
5055   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5056                                DAG.getIntPtrConstant(InsertPSMask, DL));
5057   return DAG.getBitcast(VT, Result);
5058 }
5059
5060 /// Return a vector logical shift node.
5061 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5062                          unsigned NumBits, SelectionDAG &DAG,
5063                          const TargetLowering &TLI, SDLoc dl) {
5064   assert(VT.is128BitVector() && "Unknown type for VShift");
5065   MVT ShVT = MVT::v2i64;
5066   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5067   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5068   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5069   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5070   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5071   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5072 }
5073
5074 static SDValue
5075 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5076
5077   // Check if the scalar load can be widened into a vector load. And if
5078   // the address is "base + cst" see if the cst can be "absorbed" into
5079   // the shuffle mask.
5080   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5081     SDValue Ptr = LD->getBasePtr();
5082     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5083       return SDValue();
5084     EVT PVT = LD->getValueType(0);
5085     if (PVT != MVT::i32 && PVT != MVT::f32)
5086       return SDValue();
5087
5088     int FI = -1;
5089     int64_t Offset = 0;
5090     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5091       FI = FINode->getIndex();
5092       Offset = 0;
5093     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5094                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5095       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5096       Offset = Ptr.getConstantOperandVal(1);
5097       Ptr = Ptr.getOperand(0);
5098     } else {
5099       return SDValue();
5100     }
5101
5102     // FIXME: 256-bit vector instructions don't require a strict alignment,
5103     // improve this code to support it better.
5104     unsigned RequiredAlign = VT.getSizeInBits()/8;
5105     SDValue Chain = LD->getChain();
5106     // Make sure the stack object alignment is at least 16 or 32.
5107     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5108     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5109       if (MFI->isFixedObjectIndex(FI)) {
5110         // Can't change the alignment. FIXME: It's possible to compute
5111         // the exact stack offset and reference FI + adjust offset instead.
5112         // If someone *really* cares about this. That's the way to implement it.
5113         return SDValue();
5114       } else {
5115         MFI->setObjectAlignment(FI, RequiredAlign);
5116       }
5117     }
5118
5119     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5120     // Ptr + (Offset & ~15).
5121     if (Offset < 0)
5122       return SDValue();
5123     if ((Offset % RequiredAlign) & 3)
5124       return SDValue();
5125     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5126     if (StartOffset) {
5127       SDLoc DL(Ptr);
5128       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5129                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5130     }
5131
5132     int EltNo = (Offset - StartOffset) >> 2;
5133     unsigned NumElems = VT.getVectorNumElements();
5134
5135     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5136     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5137                              LD->getPointerInfo().getWithOffset(StartOffset),
5138                              false, false, false, 0);
5139
5140     SmallVector<int, 8> Mask(NumElems, EltNo);
5141
5142     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5143   }
5144
5145   return SDValue();
5146 }
5147
5148 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5149 /// elements can be replaced by a single large load which has the same value as
5150 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5151 ///
5152 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5153 ///
5154 /// FIXME: we'd also like to handle the case where the last elements are zero
5155 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5156 /// There's even a handy isZeroNode for that purpose.
5157 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5158                                         SDLoc &DL, SelectionDAG &DAG,
5159                                         bool isAfterLegalize) {
5160   unsigned NumElems = Elts.size();
5161
5162   LoadSDNode *LDBase = nullptr;
5163   unsigned LastLoadedElt = -1U;
5164
5165   // For each element in the initializer, see if we've found a load or an undef.
5166   // If we don't find an initial load element, or later load elements are
5167   // non-consecutive, bail out.
5168   for (unsigned i = 0; i < NumElems; ++i) {
5169     SDValue Elt = Elts[i];
5170     // Look through a bitcast.
5171     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5172       Elt = Elt.getOperand(0);
5173     if (!Elt.getNode() ||
5174         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5175       return SDValue();
5176     if (!LDBase) {
5177       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5178         return SDValue();
5179       LDBase = cast<LoadSDNode>(Elt.getNode());
5180       LastLoadedElt = i;
5181       continue;
5182     }
5183     if (Elt.getOpcode() == ISD::UNDEF)
5184       continue;
5185
5186     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5187     EVT LdVT = Elt.getValueType();
5188     // Each loaded element must be the correct fractional portion of the
5189     // requested vector load.
5190     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5191       return SDValue();
5192     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5193       return SDValue();
5194     LastLoadedElt = i;
5195   }
5196
5197   // If we have found an entire vector of loads and undefs, then return a large
5198   // load of the entire vector width starting at the base pointer.  If we found
5199   // consecutive loads for the low half, generate a vzext_load node.
5200   if (LastLoadedElt == NumElems - 1) {
5201     assert(LDBase && "Did not find base load for merging consecutive loads");
5202     EVT EltVT = LDBase->getValueType(0);
5203     // Ensure that the input vector size for the merged loads matches the
5204     // cumulative size of the input elements.
5205     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5206       return SDValue();
5207
5208     if (isAfterLegalize &&
5209         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5210       return SDValue();
5211
5212     SDValue NewLd = SDValue();
5213
5214     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5215                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5216                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5217                         LDBase->getAlignment());
5218
5219     if (LDBase->hasAnyUseOfValue(1)) {
5220       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5221                                      SDValue(LDBase, 1),
5222                                      SDValue(NewLd.getNode(), 1));
5223       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5224       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5225                              SDValue(NewLd.getNode(), 1));
5226     }
5227
5228     return NewLd;
5229   }
5230
5231   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5232   //of a v4i32 / v4f32. It's probably worth generalizing.
5233   EVT EltVT = VT.getVectorElementType();
5234   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5235       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5236     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5237     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5238     SDValue ResNode =
5239         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5240                                 LDBase->getPointerInfo(),
5241                                 LDBase->getAlignment(),
5242                                 false/*isVolatile*/, true/*ReadMem*/,
5243                                 false/*WriteMem*/);
5244
5245     // Make sure the newly-created LOAD is in the same position as LDBase in
5246     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5247     // update uses of LDBase's output chain to use the TokenFactor.
5248     if (LDBase->hasAnyUseOfValue(1)) {
5249       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5250                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5251       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5252       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5253                              SDValue(ResNode.getNode(), 1));
5254     }
5255
5256     return DAG.getBitcast(VT, ResNode);
5257   }
5258   return SDValue();
5259 }
5260
5261 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5262 /// to generate a splat value for the following cases:
5263 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5264 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5265 /// a scalar load, or a constant.
5266 /// The VBROADCAST node is returned when a pattern is found,
5267 /// or SDValue() otherwise.
5268 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5269                                     SelectionDAG &DAG) {
5270   // VBROADCAST requires AVX.
5271   // TODO: Splats could be generated for non-AVX CPUs using SSE
5272   // instructions, but there's less potential gain for only 128-bit vectors.
5273   if (!Subtarget->hasAVX())
5274     return SDValue();
5275
5276   MVT VT = Op.getSimpleValueType();
5277   SDLoc dl(Op);
5278
5279   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5280          "Unsupported vector type for broadcast.");
5281
5282   SDValue Ld;
5283   bool ConstSplatVal;
5284
5285   switch (Op.getOpcode()) {
5286     default:
5287       // Unknown pattern found.
5288       return SDValue();
5289
5290     case ISD::BUILD_VECTOR: {
5291       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5292       BitVector UndefElements;
5293       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5294
5295       // We need a splat of a single value to use broadcast, and it doesn't
5296       // make any sense if the value is only in one element of the vector.
5297       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5298         return SDValue();
5299
5300       Ld = Splat;
5301       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5302                        Ld.getOpcode() == ISD::ConstantFP);
5303
5304       // Make sure that all of the users of a non-constant load are from the
5305       // BUILD_VECTOR node.
5306       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5307         return SDValue();
5308       break;
5309     }
5310
5311     case ISD::VECTOR_SHUFFLE: {
5312       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5313
5314       // Shuffles must have a splat mask where the first element is
5315       // broadcasted.
5316       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5317         return SDValue();
5318
5319       SDValue Sc = Op.getOperand(0);
5320       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5321           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5322
5323         if (!Subtarget->hasInt256())
5324           return SDValue();
5325
5326         // Use the register form of the broadcast instruction available on AVX2.
5327         if (VT.getSizeInBits() >= 256)
5328           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5329         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5330       }
5331
5332       Ld = Sc.getOperand(0);
5333       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5334                        Ld.getOpcode() == ISD::ConstantFP);
5335
5336       // The scalar_to_vector node and the suspected
5337       // load node must have exactly one user.
5338       // Constants may have multiple users.
5339
5340       // AVX-512 has register version of the broadcast
5341       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5342         Ld.getValueType().getSizeInBits() >= 32;
5343       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5344           !hasRegVer))
5345         return SDValue();
5346       break;
5347     }
5348   }
5349
5350   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5351   bool IsGE256 = (VT.getSizeInBits() >= 256);
5352
5353   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5354   // instruction to save 8 or more bytes of constant pool data.
5355   // TODO: If multiple splats are generated to load the same constant,
5356   // it may be detrimental to overall size. There needs to be a way to detect
5357   // that condition to know if this is truly a size win.
5358   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5359
5360   // Handle broadcasting a single constant scalar from the constant pool
5361   // into a vector.
5362   // On Sandybridge (no AVX2), it is still better to load a constant vector
5363   // from the constant pool and not to broadcast it from a scalar.
5364   // But override that restriction when optimizing for size.
5365   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5366   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5367     EVT CVT = Ld.getValueType();
5368     assert(!CVT.isVector() && "Must not broadcast a vector type");
5369
5370     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5371     // For size optimization, also splat v2f64 and v2i64, and for size opt
5372     // with AVX2, also splat i8 and i16.
5373     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5374     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5375         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5376       const Constant *C = nullptr;
5377       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5378         C = CI->getConstantIntValue();
5379       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5380         C = CF->getConstantFPValue();
5381
5382       assert(C && "Invalid constant type");
5383
5384       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5385       SDValue CP =
5386           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5387       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5388       Ld = DAG.getLoad(
5389           CVT, dl, DAG.getEntryNode(), CP,
5390           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5391           false, false, Alignment);
5392
5393       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5394     }
5395   }
5396
5397   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5398
5399   // Handle AVX2 in-register broadcasts.
5400   if (!IsLoad && Subtarget->hasInt256() &&
5401       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5402     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5403
5404   // The scalar source must be a normal load.
5405   if (!IsLoad)
5406     return SDValue();
5407
5408   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5409       (Subtarget->hasVLX() && ScalarSize == 64))
5410     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5411
5412   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5413   // double since there is no vbroadcastsd xmm
5414   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5415     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5416       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5417   }
5418
5419   // Unsupported broadcast.
5420   return SDValue();
5421 }
5422
5423 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5424 /// underlying vector and index.
5425 ///
5426 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5427 /// index.
5428 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5429                                          SDValue ExtIdx) {
5430   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5431   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5432     return Idx;
5433
5434   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5435   // lowered this:
5436   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5437   // to:
5438   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5439   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5440   //                           undef)
5441   //                       Constant<0>)
5442   // In this case the vector is the extract_subvector expression and the index
5443   // is 2, as specified by the shuffle.
5444   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5445   SDValue ShuffleVec = SVOp->getOperand(0);
5446   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5447   assert(ShuffleVecVT.getVectorElementType() ==
5448          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5449
5450   int ShuffleIdx = SVOp->getMaskElt(Idx);
5451   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5452     ExtractedFromVec = ShuffleVec;
5453     return ShuffleIdx;
5454   }
5455   return Idx;
5456 }
5457
5458 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5459   MVT VT = Op.getSimpleValueType();
5460
5461   // Skip if insert_vec_elt is not supported.
5462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5463   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5464     return SDValue();
5465
5466   SDLoc DL(Op);
5467   unsigned NumElems = Op.getNumOperands();
5468
5469   SDValue VecIn1;
5470   SDValue VecIn2;
5471   SmallVector<unsigned, 4> InsertIndices;
5472   SmallVector<int, 8> Mask(NumElems, -1);
5473
5474   for (unsigned i = 0; i != NumElems; ++i) {
5475     unsigned Opc = Op.getOperand(i).getOpcode();
5476
5477     if (Opc == ISD::UNDEF)
5478       continue;
5479
5480     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5481       // Quit if more than 1 elements need inserting.
5482       if (InsertIndices.size() > 1)
5483         return SDValue();
5484
5485       InsertIndices.push_back(i);
5486       continue;
5487     }
5488
5489     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5490     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5491     // Quit if non-constant index.
5492     if (!isa<ConstantSDNode>(ExtIdx))
5493       return SDValue();
5494     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5495
5496     // Quit if extracted from vector of different type.
5497     if (ExtractedFromVec.getValueType() != VT)
5498       return SDValue();
5499
5500     if (!VecIn1.getNode())
5501       VecIn1 = ExtractedFromVec;
5502     else if (VecIn1 != ExtractedFromVec) {
5503       if (!VecIn2.getNode())
5504         VecIn2 = ExtractedFromVec;
5505       else if (VecIn2 != ExtractedFromVec)
5506         // Quit if more than 2 vectors to shuffle
5507         return SDValue();
5508     }
5509
5510     if (ExtractedFromVec == VecIn1)
5511       Mask[i] = Idx;
5512     else if (ExtractedFromVec == VecIn2)
5513       Mask[i] = Idx + NumElems;
5514   }
5515
5516   if (!VecIn1.getNode())
5517     return SDValue();
5518
5519   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5520   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5521   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5522     unsigned Idx = InsertIndices[i];
5523     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5524                      DAG.getIntPtrConstant(Idx, DL));
5525   }
5526
5527   return NV;
5528 }
5529
5530 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5531   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5532          Op.getScalarValueSizeInBits() == 1 &&
5533          "Can not convert non-constant vector");
5534   uint64_t Immediate = 0;
5535   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5536     SDValue In = Op.getOperand(idx);
5537     if (In.getOpcode() != ISD::UNDEF)
5538       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5539   }
5540   SDLoc dl(Op);
5541   MVT VT =
5542    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5543   return DAG.getConstant(Immediate, dl, VT);
5544 }
5545 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5546 SDValue
5547 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5548
5549   MVT VT = Op.getSimpleValueType();
5550   assert((VT.getVectorElementType() == MVT::i1) &&
5551          "Unexpected type in LowerBUILD_VECTORvXi1!");
5552
5553   SDLoc dl(Op);
5554   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5555     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5556     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5557     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5558   }
5559
5560   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5561     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5562     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5563     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5564   }
5565
5566   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5567     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5568     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5569       return DAG.getBitcast(VT, Imm);
5570     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5571     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5572                         DAG.getIntPtrConstant(0, dl));
5573   }
5574
5575   // Vector has one or more non-const elements
5576   uint64_t Immediate = 0;
5577   SmallVector<unsigned, 16> NonConstIdx;
5578   bool IsSplat = true;
5579   bool HasConstElts = false;
5580   int SplatIdx = -1;
5581   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5582     SDValue In = Op.getOperand(idx);
5583     if (In.getOpcode() == ISD::UNDEF)
5584       continue;
5585     if (!isa<ConstantSDNode>(In))
5586       NonConstIdx.push_back(idx);
5587     else {
5588       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5589       HasConstElts = true;
5590     }
5591     if (SplatIdx == -1)
5592       SplatIdx = idx;
5593     else if (In != Op.getOperand(SplatIdx))
5594       IsSplat = false;
5595   }
5596
5597   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5598   if (IsSplat)
5599     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5600                        DAG.getConstant(1, dl, VT),
5601                        DAG.getConstant(0, dl, VT));
5602
5603   // insert elements one by one
5604   SDValue DstVec;
5605   SDValue Imm;
5606   if (Immediate) {
5607     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5608     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5609   }
5610   else if (HasConstElts)
5611     Imm = DAG.getConstant(0, dl, VT);
5612   else
5613     Imm = DAG.getUNDEF(VT);
5614   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5615     DstVec = DAG.getBitcast(VT, Imm);
5616   else {
5617     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5618     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5619                          DAG.getIntPtrConstant(0, dl));
5620   }
5621
5622   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5623     unsigned InsertIdx = NonConstIdx[i];
5624     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5625                          Op.getOperand(InsertIdx),
5626                          DAG.getIntPtrConstant(InsertIdx, dl));
5627   }
5628   return DstVec;
5629 }
5630
5631 /// \brief Return true if \p N implements a horizontal binop and return the
5632 /// operands for the horizontal binop into V0 and V1.
5633 ///
5634 /// This is a helper function of LowerToHorizontalOp().
5635 /// This function checks that the build_vector \p N in input implements a
5636 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5637 /// operation to match.
5638 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5639 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5640 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5641 /// arithmetic sub.
5642 ///
5643 /// This function only analyzes elements of \p N whose indices are
5644 /// in range [BaseIdx, LastIdx).
5645 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5646                               SelectionDAG &DAG,
5647                               unsigned BaseIdx, unsigned LastIdx,
5648                               SDValue &V0, SDValue &V1) {
5649   EVT VT = N->getValueType(0);
5650
5651   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5652   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5653          "Invalid Vector in input!");
5654
5655   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5656   bool CanFold = true;
5657   unsigned ExpectedVExtractIdx = BaseIdx;
5658   unsigned NumElts = LastIdx - BaseIdx;
5659   V0 = DAG.getUNDEF(VT);
5660   V1 = DAG.getUNDEF(VT);
5661
5662   // Check if N implements a horizontal binop.
5663   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5664     SDValue Op = N->getOperand(i + BaseIdx);
5665
5666     // Skip UNDEFs.
5667     if (Op->getOpcode() == ISD::UNDEF) {
5668       // Update the expected vector extract index.
5669       if (i * 2 == NumElts)
5670         ExpectedVExtractIdx = BaseIdx;
5671       ExpectedVExtractIdx += 2;
5672       continue;
5673     }
5674
5675     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5676
5677     if (!CanFold)
5678       break;
5679
5680     SDValue Op0 = Op.getOperand(0);
5681     SDValue Op1 = Op.getOperand(1);
5682
5683     // Try to match the following pattern:
5684     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5685     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5686         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5687         Op0.getOperand(0) == Op1.getOperand(0) &&
5688         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5689         isa<ConstantSDNode>(Op1.getOperand(1)));
5690     if (!CanFold)
5691       break;
5692
5693     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5694     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5695
5696     if (i * 2 < NumElts) {
5697       if (V0.getOpcode() == ISD::UNDEF) {
5698         V0 = Op0.getOperand(0);
5699         if (V0.getValueType() != VT)
5700           return false;
5701       }
5702     } else {
5703       if (V1.getOpcode() == ISD::UNDEF) {
5704         V1 = Op0.getOperand(0);
5705         if (V1.getValueType() != VT)
5706           return false;
5707       }
5708       if (i * 2 == NumElts)
5709         ExpectedVExtractIdx = BaseIdx;
5710     }
5711
5712     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5713     if (I0 == ExpectedVExtractIdx)
5714       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5715     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5716       // Try to match the following dag sequence:
5717       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5718       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5719     } else
5720       CanFold = false;
5721
5722     ExpectedVExtractIdx += 2;
5723   }
5724
5725   return CanFold;
5726 }
5727
5728 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5729 /// a concat_vector.
5730 ///
5731 /// This is a helper function of LowerToHorizontalOp().
5732 /// This function expects two 256-bit vectors called V0 and V1.
5733 /// At first, each vector is split into two separate 128-bit vectors.
5734 /// Then, the resulting 128-bit vectors are used to implement two
5735 /// horizontal binary operations.
5736 ///
5737 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5738 ///
5739 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5740 /// the two new horizontal binop.
5741 /// When Mode is set, the first horizontal binop dag node would take as input
5742 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5743 /// horizontal binop dag node would take as input the lower 128-bit of V1
5744 /// and the upper 128-bit of V1.
5745 ///   Example:
5746 ///     HADD V0_LO, V0_HI
5747 ///     HADD V1_LO, V1_HI
5748 ///
5749 /// Otherwise, the first horizontal binop dag node takes as input the lower
5750 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5751 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5752 ///   Example:
5753 ///     HADD V0_LO, V1_LO
5754 ///     HADD V0_HI, V1_HI
5755 ///
5756 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5757 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5758 /// the upper 128-bits of the result.
5759 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5760                                      SDLoc DL, SelectionDAG &DAG,
5761                                      unsigned X86Opcode, bool Mode,
5762                                      bool isUndefLO, bool isUndefHI) {
5763   EVT VT = V0.getValueType();
5764   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5765          "Invalid nodes in input!");
5766
5767   unsigned NumElts = VT.getVectorNumElements();
5768   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5769   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5770   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5771   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5772   EVT NewVT = V0_LO.getValueType();
5773
5774   SDValue LO = DAG.getUNDEF(NewVT);
5775   SDValue HI = DAG.getUNDEF(NewVT);
5776
5777   if (Mode) {
5778     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5779     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5780       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5781     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5782       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5783   } else {
5784     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5785     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5786                        V1_LO->getOpcode() != ISD::UNDEF))
5787       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5788
5789     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5790                        V1_HI->getOpcode() != ISD::UNDEF))
5791       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5792   }
5793
5794   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5795 }
5796
5797 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5798 /// node.
5799 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5800                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5801   EVT VT = BV->getValueType(0);
5802   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5803       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5804     return SDValue();
5805
5806   SDLoc DL(BV);
5807   unsigned NumElts = VT.getVectorNumElements();
5808   SDValue InVec0 = DAG.getUNDEF(VT);
5809   SDValue InVec1 = DAG.getUNDEF(VT);
5810
5811   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5812           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5813
5814   // Odd-numbered elements in the input build vector are obtained from
5815   // adding two integer/float elements.
5816   // Even-numbered elements in the input build vector are obtained from
5817   // subtracting two integer/float elements.
5818   unsigned ExpectedOpcode = ISD::FSUB;
5819   unsigned NextExpectedOpcode = ISD::FADD;
5820   bool AddFound = false;
5821   bool SubFound = false;
5822
5823   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5824     SDValue Op = BV->getOperand(i);
5825
5826     // Skip 'undef' values.
5827     unsigned Opcode = Op.getOpcode();
5828     if (Opcode == ISD::UNDEF) {
5829       std::swap(ExpectedOpcode, NextExpectedOpcode);
5830       continue;
5831     }
5832
5833     // Early exit if we found an unexpected opcode.
5834     if (Opcode != ExpectedOpcode)
5835       return SDValue();
5836
5837     SDValue Op0 = Op.getOperand(0);
5838     SDValue Op1 = Op.getOperand(1);
5839
5840     // Try to match the following pattern:
5841     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5842     // Early exit if we cannot match that sequence.
5843     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5844         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5845         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5846         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5847         Op0.getOperand(1) != Op1.getOperand(1))
5848       return SDValue();
5849
5850     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5851     if (I0 != i)
5852       return SDValue();
5853
5854     // We found a valid add/sub node. Update the information accordingly.
5855     if (i & 1)
5856       AddFound = true;
5857     else
5858       SubFound = true;
5859
5860     // Update InVec0 and InVec1.
5861     if (InVec0.getOpcode() == ISD::UNDEF) {
5862       InVec0 = Op0.getOperand(0);
5863       if (InVec0.getValueType() != VT)
5864         return SDValue();
5865     }
5866     if (InVec1.getOpcode() == ISD::UNDEF) {
5867       InVec1 = Op1.getOperand(0);
5868       if (InVec1.getValueType() != VT)
5869         return SDValue();
5870     }
5871
5872     // Make sure that operands in input to each add/sub node always
5873     // come from a same pair of vectors.
5874     if (InVec0 != Op0.getOperand(0)) {
5875       if (ExpectedOpcode == ISD::FSUB)
5876         return SDValue();
5877
5878       // FADD is commutable. Try to commute the operands
5879       // and then test again.
5880       std::swap(Op0, Op1);
5881       if (InVec0 != Op0.getOperand(0))
5882         return SDValue();
5883     }
5884
5885     if (InVec1 != Op1.getOperand(0))
5886       return SDValue();
5887
5888     // Update the pair of expected opcodes.
5889     std::swap(ExpectedOpcode, NextExpectedOpcode);
5890   }
5891
5892   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5893   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5894       InVec1.getOpcode() != ISD::UNDEF)
5895     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5896
5897   return SDValue();
5898 }
5899
5900 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5901 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5902                                    const X86Subtarget *Subtarget,
5903                                    SelectionDAG &DAG) {
5904   EVT VT = BV->getValueType(0);
5905   unsigned NumElts = VT.getVectorNumElements();
5906   unsigned NumUndefsLO = 0;
5907   unsigned NumUndefsHI = 0;
5908   unsigned Half = NumElts/2;
5909
5910   // Count the number of UNDEF operands in the build_vector in input.
5911   for (unsigned i = 0, e = Half; i != e; ++i)
5912     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5913       NumUndefsLO++;
5914
5915   for (unsigned i = Half, e = NumElts; i != e; ++i)
5916     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5917       NumUndefsHI++;
5918
5919   // Early exit if this is either a build_vector of all UNDEFs or all the
5920   // operands but one are UNDEF.
5921   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5922     return SDValue();
5923
5924   SDLoc DL(BV);
5925   SDValue InVec0, InVec1;
5926   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5927     // Try to match an SSE3 float HADD/HSUB.
5928     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5929       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5930
5931     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5932       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5933   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5934     // Try to match an SSSE3 integer HADD/HSUB.
5935     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5936       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5937
5938     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5939       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5940   }
5941
5942   if (!Subtarget->hasAVX())
5943     return SDValue();
5944
5945   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5946     // Try to match an AVX horizontal add/sub of packed single/double
5947     // precision floating point values from 256-bit vectors.
5948     SDValue InVec2, InVec3;
5949     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5950         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5951         ((InVec0.getOpcode() == ISD::UNDEF ||
5952           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5953         ((InVec1.getOpcode() == ISD::UNDEF ||
5954           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5955       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5956
5957     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5958         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5959         ((InVec0.getOpcode() == ISD::UNDEF ||
5960           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5961         ((InVec1.getOpcode() == ISD::UNDEF ||
5962           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5963       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5964   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5965     // Try to match an AVX2 horizontal add/sub of signed integers.
5966     SDValue InVec2, InVec3;
5967     unsigned X86Opcode;
5968     bool CanFold = true;
5969
5970     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5971         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5972         ((InVec0.getOpcode() == ISD::UNDEF ||
5973           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5974         ((InVec1.getOpcode() == ISD::UNDEF ||
5975           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5976       X86Opcode = X86ISD::HADD;
5977     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5978         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5979         ((InVec0.getOpcode() == ISD::UNDEF ||
5980           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5981         ((InVec1.getOpcode() == ISD::UNDEF ||
5982           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5983       X86Opcode = X86ISD::HSUB;
5984     else
5985       CanFold = false;
5986
5987     if (CanFold) {
5988       // Fold this build_vector into a single horizontal add/sub.
5989       // Do this only if the target has AVX2.
5990       if (Subtarget->hasAVX2())
5991         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5992
5993       // Do not try to expand this build_vector into a pair of horizontal
5994       // add/sub if we can emit a pair of scalar add/sub.
5995       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5996         return SDValue();
5997
5998       // Convert this build_vector into a pair of horizontal binop followed by
5999       // a concat vector.
6000       bool isUndefLO = NumUndefsLO == Half;
6001       bool isUndefHI = NumUndefsHI == Half;
6002       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6003                                    isUndefLO, isUndefHI);
6004     }
6005   }
6006
6007   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6008        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6009     unsigned X86Opcode;
6010     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6011       X86Opcode = X86ISD::HADD;
6012     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6013       X86Opcode = X86ISD::HSUB;
6014     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6015       X86Opcode = X86ISD::FHADD;
6016     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6017       X86Opcode = X86ISD::FHSUB;
6018     else
6019       return SDValue();
6020
6021     // Don't try to expand this build_vector into a pair of horizontal add/sub
6022     // if we can simply emit a pair of scalar add/sub.
6023     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6024       return SDValue();
6025
6026     // Convert this build_vector into two horizontal add/sub followed by
6027     // a concat vector.
6028     bool isUndefLO = NumUndefsLO == Half;
6029     bool isUndefHI = NumUndefsHI == Half;
6030     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6031                                  isUndefLO, isUndefHI);
6032   }
6033
6034   return SDValue();
6035 }
6036
6037 SDValue
6038 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6039   SDLoc dl(Op);
6040
6041   MVT VT = Op.getSimpleValueType();
6042   MVT ExtVT = VT.getVectorElementType();
6043   unsigned NumElems = Op.getNumOperands();
6044
6045   // Generate vectors for predicate vectors.
6046   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6047     return LowerBUILD_VECTORvXi1(Op, DAG);
6048
6049   // Vectors containing all zeros can be matched by pxor and xorps later
6050   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6051     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6052     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6053     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6054       return Op;
6055
6056     return getZeroVector(VT, Subtarget, DAG, dl);
6057   }
6058
6059   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6060   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6061   // vpcmpeqd on 256-bit vectors.
6062   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6063     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6064       return Op;
6065
6066     if (!VT.is512BitVector())
6067       return getOnesVector(VT, Subtarget, DAG, dl);
6068   }
6069
6070   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6071   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6072     return AddSub;
6073   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6074     return HorizontalOp;
6075   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6076     return Broadcast;
6077
6078   unsigned EVTBits = ExtVT.getSizeInBits();
6079
6080   unsigned NumZero  = 0;
6081   unsigned NumNonZero = 0;
6082   unsigned NonZeros = 0;
6083   bool IsAllConstants = true;
6084   SmallSet<SDValue, 8> Values;
6085   for (unsigned i = 0; i < NumElems; ++i) {
6086     SDValue Elt = Op.getOperand(i);
6087     if (Elt.getOpcode() == ISD::UNDEF)
6088       continue;
6089     Values.insert(Elt);
6090     if (Elt.getOpcode() != ISD::Constant &&
6091         Elt.getOpcode() != ISD::ConstantFP)
6092       IsAllConstants = false;
6093     if (X86::isZeroNode(Elt))
6094       NumZero++;
6095     else {
6096       NonZeros |= (1 << i);
6097       NumNonZero++;
6098     }
6099   }
6100
6101   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6102   if (NumNonZero == 0)
6103     return DAG.getUNDEF(VT);
6104
6105   // Special case for single non-zero, non-undef, element.
6106   if (NumNonZero == 1) {
6107     unsigned Idx = countTrailingZeros(NonZeros);
6108     SDValue Item = Op.getOperand(Idx);
6109
6110     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6111     // the value are obviously zero, truncate the value to i32 and do the
6112     // insertion that way.  Only do this if the value is non-constant or if the
6113     // value is a constant being inserted into element 0.  It is cheaper to do
6114     // a constant pool load than it is to do a movd + shuffle.
6115     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6116         (!IsAllConstants || Idx == 0)) {
6117       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6118         // Handle SSE only.
6119         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6120         EVT VecVT = MVT::v4i32;
6121
6122         // Truncate the value (which may itself be a constant) to i32, and
6123         // convert it to a vector with movd (S2V+shuffle to zero extend).
6124         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6125         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6126         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6127                                       Item, Idx * 2, true, Subtarget, DAG));
6128       }
6129     }
6130
6131     // If we have a constant or non-constant insertion into the low element of
6132     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6133     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6134     // depending on what the source datatype is.
6135     if (Idx == 0) {
6136       if (NumZero == 0)
6137         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6138
6139       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6140           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6141         if (VT.is512BitVector()) {
6142           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6143           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6144                              Item, DAG.getIntPtrConstant(0, dl));
6145         }
6146         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6147                "Expected an SSE value type!");
6148         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6149         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6150         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6151       }
6152
6153       // We can't directly insert an i8 or i16 into a vector, so zero extend
6154       // it to i32 first.
6155       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6156         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6157         if (VT.is256BitVector()) {
6158           if (Subtarget->hasAVX()) {
6159             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6160             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6161           } else {
6162             // Without AVX, we need to extend to a 128-bit vector and then
6163             // insert into the 256-bit vector.
6164             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6165             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6166             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6167           }
6168         } else {
6169           assert(VT.is128BitVector() && "Expected an SSE value type!");
6170           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6171           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6172         }
6173         return DAG.getBitcast(VT, Item);
6174       }
6175     }
6176
6177     // Is it a vector logical left shift?
6178     if (NumElems == 2 && Idx == 1 &&
6179         X86::isZeroNode(Op.getOperand(0)) &&
6180         !X86::isZeroNode(Op.getOperand(1))) {
6181       unsigned NumBits = VT.getSizeInBits();
6182       return getVShift(true, VT,
6183                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6184                                    VT, Op.getOperand(1)),
6185                        NumBits/2, DAG, *this, dl);
6186     }
6187
6188     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6189       return SDValue();
6190
6191     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6192     // is a non-constant being inserted into an element other than the low one,
6193     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6194     // movd/movss) to move this into the low element, then shuffle it into
6195     // place.
6196     if (EVTBits == 32) {
6197       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6198       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6199     }
6200   }
6201
6202   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6203   if (Values.size() == 1) {
6204     if (EVTBits == 32) {
6205       // Instead of a shuffle like this:
6206       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6207       // Check if it's possible to issue this instead.
6208       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6209       unsigned Idx = countTrailingZeros(NonZeros);
6210       SDValue Item = Op.getOperand(Idx);
6211       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6212         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6213     }
6214     return SDValue();
6215   }
6216
6217   // A vector full of immediates; various special cases are already
6218   // handled, so this is best done with a single constant-pool load.
6219   if (IsAllConstants)
6220     return SDValue();
6221
6222   // For AVX-length vectors, see if we can use a vector load to get all of the
6223   // elements, otherwise build the individual 128-bit pieces and use
6224   // shuffles to put them in place.
6225   if (VT.is256BitVector() || VT.is512BitVector()) {
6226     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6227
6228     // Check for a build vector of consecutive loads.
6229     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6230       return LD;
6231
6232     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6233
6234     // Build both the lower and upper subvector.
6235     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6236                                 makeArrayRef(&V[0], NumElems/2));
6237     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6238                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6239
6240     // Recreate the wider vector with the lower and upper part.
6241     if (VT.is256BitVector())
6242       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6243     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6244   }
6245
6246   // Let legalizer expand 2-wide build_vectors.
6247   if (EVTBits == 64) {
6248     if (NumNonZero == 1) {
6249       // One half is zero or undef.
6250       unsigned Idx = countTrailingZeros(NonZeros);
6251       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6252                                  Op.getOperand(Idx));
6253       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6254     }
6255     return SDValue();
6256   }
6257
6258   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6259   if (EVTBits == 8 && NumElems == 16)
6260     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6261                                         Subtarget, *this))
6262       return V;
6263
6264   if (EVTBits == 16 && NumElems == 8)
6265     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6266                                       Subtarget, *this))
6267       return V;
6268
6269   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6270   if (EVTBits == 32 && NumElems == 4)
6271     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6272       return V;
6273
6274   // If element VT is == 32 bits, turn it into a number of shuffles.
6275   SmallVector<SDValue, 8> V(NumElems);
6276   if (NumElems == 4 && NumZero > 0) {
6277     for (unsigned i = 0; i < 4; ++i) {
6278       bool isZero = !(NonZeros & (1 << i));
6279       if (isZero)
6280         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6281       else
6282         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6283     }
6284
6285     for (unsigned i = 0; i < 2; ++i) {
6286       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6287         default: break;
6288         case 0:
6289           V[i] = V[i*2];  // Must be a zero vector.
6290           break;
6291         case 1:
6292           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6293           break;
6294         case 2:
6295           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6296           break;
6297         case 3:
6298           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6299           break;
6300       }
6301     }
6302
6303     bool Reverse1 = (NonZeros & 0x3) == 2;
6304     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6305     int MaskVec[] = {
6306       Reverse1 ? 1 : 0,
6307       Reverse1 ? 0 : 1,
6308       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6309       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6310     };
6311     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6312   }
6313
6314   if (Values.size() > 1 && VT.is128BitVector()) {
6315     // Check for a build vector of consecutive loads.
6316     for (unsigned i = 0; i < NumElems; ++i)
6317       V[i] = Op.getOperand(i);
6318
6319     // Check for elements which are consecutive loads.
6320     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6321       return LD;
6322
6323     // Check for a build vector from mostly shuffle plus few inserting.
6324     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6325       return Sh;
6326
6327     // For SSE 4.1, use insertps to put the high elements into the low element.
6328     if (Subtarget->hasSSE41()) {
6329       SDValue Result;
6330       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6331         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6332       else
6333         Result = DAG.getUNDEF(VT);
6334
6335       for (unsigned i = 1; i < NumElems; ++i) {
6336         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6337         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6338                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6339       }
6340       return Result;
6341     }
6342
6343     // Otherwise, expand into a number of unpckl*, start by extending each of
6344     // our (non-undef) elements to the full vector width with the element in the
6345     // bottom slot of the vector (which generates no code for SSE).
6346     for (unsigned i = 0; i < NumElems; ++i) {
6347       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6348         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6349       else
6350         V[i] = DAG.getUNDEF(VT);
6351     }
6352
6353     // Next, we iteratively mix elements, e.g. for v4f32:
6354     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6355     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6356     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6357     unsigned EltStride = NumElems >> 1;
6358     while (EltStride != 0) {
6359       for (unsigned i = 0; i < EltStride; ++i) {
6360         // If V[i+EltStride] is undef and this is the first round of mixing,
6361         // then it is safe to just drop this shuffle: V[i] is already in the
6362         // right place, the one element (since it's the first round) being
6363         // inserted as undef can be dropped.  This isn't safe for successive
6364         // rounds because they will permute elements within both vectors.
6365         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6366             EltStride == NumElems/2)
6367           continue;
6368
6369         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6370       }
6371       EltStride >>= 1;
6372     }
6373     return V[0];
6374   }
6375   return SDValue();
6376 }
6377
6378 // 256-bit AVX can use the vinsertf128 instruction
6379 // to create 256-bit vectors from two other 128-bit ones.
6380 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6381   SDLoc dl(Op);
6382   MVT ResVT = Op.getSimpleValueType();
6383
6384   assert((ResVT.is256BitVector() ||
6385           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6386
6387   SDValue V1 = Op.getOperand(0);
6388   SDValue V2 = Op.getOperand(1);
6389   unsigned NumElems = ResVT.getVectorNumElements();
6390   if (ResVT.is256BitVector())
6391     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6392
6393   if (Op.getNumOperands() == 4) {
6394     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6395                                 ResVT.getVectorNumElements()/2);
6396     SDValue V3 = Op.getOperand(2);
6397     SDValue V4 = Op.getOperand(3);
6398     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6399       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6400   }
6401   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6402 }
6403
6404 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6405                                        const X86Subtarget *Subtarget,
6406                                        SelectionDAG & DAG) {
6407   SDLoc dl(Op);
6408   MVT ResVT = Op.getSimpleValueType();
6409   unsigned NumOfOperands = Op.getNumOperands();
6410
6411   assert(isPowerOf2_32(NumOfOperands) &&
6412          "Unexpected number of operands in CONCAT_VECTORS");
6413
6414   if (NumOfOperands > 2) {
6415     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6416                                   ResVT.getVectorNumElements()/2);
6417     SmallVector<SDValue, 2> Ops;
6418     for (unsigned i = 0; i < NumOfOperands/2; i++)
6419       Ops.push_back(Op.getOperand(i));
6420     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6421     Ops.clear();
6422     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6423       Ops.push_back(Op.getOperand(i));
6424     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6425     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6426   }
6427
6428   SDValue V1 = Op.getOperand(0);
6429   SDValue V2 = Op.getOperand(1);
6430   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6431   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6432
6433   if (IsZeroV1 && IsZeroV2)
6434     return getZeroVector(ResVT, Subtarget, DAG, dl);
6435
6436   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6437   SDValue Undef = DAG.getUNDEF(ResVT);
6438   unsigned NumElems = ResVT.getVectorNumElements();
6439   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6440
6441   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6442   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6443   if (IsZeroV1)
6444     return V2;
6445
6446   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6447   // Zero the upper bits of V1
6448   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6449   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6450   if (IsZeroV2)
6451     return V1;
6452   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6453 }
6454
6455 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6456                                    const X86Subtarget *Subtarget,
6457                                    SelectionDAG &DAG) {
6458   MVT VT = Op.getSimpleValueType();
6459   if (VT.getVectorElementType() == MVT::i1)
6460     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6461
6462   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6463          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6464           Op.getNumOperands() == 4)));
6465
6466   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6467   // from two other 128-bit ones.
6468
6469   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6470   return LowerAVXCONCAT_VECTORS(Op, DAG);
6471 }
6472
6473 //===----------------------------------------------------------------------===//
6474 // Vector shuffle lowering
6475 //
6476 // This is an experimental code path for lowering vector shuffles on x86. It is
6477 // designed to handle arbitrary vector shuffles and blends, gracefully
6478 // degrading performance as necessary. It works hard to recognize idiomatic
6479 // shuffles and lower them to optimal instruction patterns without leaving
6480 // a framework that allows reasonably efficient handling of all vector shuffle
6481 // patterns.
6482 //===----------------------------------------------------------------------===//
6483
6484 /// \brief Tiny helper function to identify a no-op mask.
6485 ///
6486 /// This is a somewhat boring predicate function. It checks whether the mask
6487 /// array input, which is assumed to be a single-input shuffle mask of the kind
6488 /// used by the X86 shuffle instructions (not a fully general
6489 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6490 /// in-place shuffle are 'no-op's.
6491 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6492   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6493     if (Mask[i] != -1 && Mask[i] != i)
6494       return false;
6495   return true;
6496 }
6497
6498 /// \brief Helper function to classify a mask as a single-input mask.
6499 ///
6500 /// This isn't a generic single-input test because in the vector shuffle
6501 /// lowering we canonicalize single inputs to be the first input operand. This
6502 /// means we can more quickly test for a single input by only checking whether
6503 /// an input from the second operand exists. We also assume that the size of
6504 /// mask corresponds to the size of the input vectors which isn't true in the
6505 /// fully general case.
6506 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6507   for (int M : Mask)
6508     if (M >= (int)Mask.size())
6509       return false;
6510   return true;
6511 }
6512
6513 /// \brief Test whether there are elements crossing 128-bit lanes in this
6514 /// shuffle mask.
6515 ///
6516 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6517 /// and we routinely test for these.
6518 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6519   int LaneSize = 128 / VT.getScalarSizeInBits();
6520   int Size = Mask.size();
6521   for (int i = 0; i < Size; ++i)
6522     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6523       return true;
6524   return false;
6525 }
6526
6527 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6528 ///
6529 /// This checks a shuffle mask to see if it is performing the same
6530 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6531 /// that it is also not lane-crossing. It may however involve a blend from the
6532 /// same lane of a second vector.
6533 ///
6534 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6535 /// non-trivial to compute in the face of undef lanes. The representation is
6536 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6537 /// entries from both V1 and V2 inputs to the wider mask.
6538 static bool
6539 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6540                                 SmallVectorImpl<int> &RepeatedMask) {
6541   int LaneSize = 128 / VT.getScalarSizeInBits();
6542   RepeatedMask.resize(LaneSize, -1);
6543   int Size = Mask.size();
6544   for (int i = 0; i < Size; ++i) {
6545     if (Mask[i] < 0)
6546       continue;
6547     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6548       // This entry crosses lanes, so there is no way to model this shuffle.
6549       return false;
6550
6551     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6552     if (RepeatedMask[i % LaneSize] == -1)
6553       // This is the first non-undef entry in this slot of a 128-bit lane.
6554       RepeatedMask[i % LaneSize] =
6555           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6556     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6557       // Found a mismatch with the repeated mask.
6558       return false;
6559   }
6560   return true;
6561 }
6562
6563 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6564 /// arguments.
6565 ///
6566 /// This is a fast way to test a shuffle mask against a fixed pattern:
6567 ///
6568 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6569 ///
6570 /// It returns true if the mask is exactly as wide as the argument list, and
6571 /// each element of the mask is either -1 (signifying undef) or the value given
6572 /// in the argument.
6573 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6574                                 ArrayRef<int> ExpectedMask) {
6575   if (Mask.size() != ExpectedMask.size())
6576     return false;
6577
6578   int Size = Mask.size();
6579
6580   // If the values are build vectors, we can look through them to find
6581   // equivalent inputs that make the shuffles equivalent.
6582   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6583   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6584
6585   for (int i = 0; i < Size; ++i)
6586     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6587       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6588       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6589       if (!MaskBV || !ExpectedBV ||
6590           MaskBV->getOperand(Mask[i] % Size) !=
6591               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6592         return false;
6593     }
6594
6595   return true;
6596 }
6597
6598 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6599 ///
6600 /// This helper function produces an 8-bit shuffle immediate corresponding to
6601 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6602 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6603 /// example.
6604 ///
6605 /// NB: We rely heavily on "undef" masks preserving the input lane.
6606 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6607                                           SelectionDAG &DAG) {
6608   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6609   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6610   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6611   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6612   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6613
6614   unsigned Imm = 0;
6615   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6616   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6617   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6618   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6619   return DAG.getConstant(Imm, DL, MVT::i8);
6620 }
6621
6622 /// \brief Compute whether each element of a shuffle is zeroable.
6623 ///
6624 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6625 /// Either it is an undef element in the shuffle mask, the element of the input
6626 /// referenced is undef, or the element of the input referenced is known to be
6627 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6628 /// as many lanes with this technique as possible to simplify the remaining
6629 /// shuffle.
6630 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6631                                                      SDValue V1, SDValue V2) {
6632   SmallBitVector Zeroable(Mask.size(), false);
6633
6634   while (V1.getOpcode() == ISD::BITCAST)
6635     V1 = V1->getOperand(0);
6636   while (V2.getOpcode() == ISD::BITCAST)
6637     V2 = V2->getOperand(0);
6638
6639   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6640   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6641
6642   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6643     int M = Mask[i];
6644     // Handle the easy cases.
6645     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6646       Zeroable[i] = true;
6647       continue;
6648     }
6649
6650     // If this is an index into a build_vector node (which has the same number
6651     // of elements), dig out the input value and use it.
6652     SDValue V = M < Size ? V1 : V2;
6653     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6654       continue;
6655
6656     SDValue Input = V.getOperand(M % Size);
6657     // The UNDEF opcode check really should be dead code here, but not quite
6658     // worth asserting on (it isn't invalid, just unexpected).
6659     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6660       Zeroable[i] = true;
6661   }
6662
6663   return Zeroable;
6664 }
6665
6666 // X86 has dedicated unpack instructions that can handle specific blend
6667 // operations: UNPCKH and UNPCKL.
6668 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6669                                            SDValue V1, SDValue V2,
6670                                            SelectionDAG &DAG) {
6671   int NumElts = VT.getVectorNumElements();
6672   bool Unpckl = true;
6673   bool Unpckh = true;
6674   bool UnpcklSwapped = true;
6675   bool UnpckhSwapped = true;
6676   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6677
6678   for (int i = 0; i < NumElts; ++i) {
6679     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6680
6681     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6682     int HiPos = LoPos + NumEltsInLane / 2;
6683     int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6684     int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6685
6686     if (Mask[i] == -1)
6687       continue;
6688     if (Mask[i] != LoPos)
6689       Unpckl = false;
6690     if (Mask[i] != HiPos)
6691       Unpckh = false;
6692     if (Mask[i] != LoPosSwapped)
6693       UnpcklSwapped = false;
6694     if (Mask[i] != HiPosSwapped)
6695       UnpckhSwapped = false;
6696     if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6697       return SDValue();
6698   }
6699   if (Unpckl)
6700     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6701   if (Unpckh)
6702     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6703   if (UnpcklSwapped)
6704     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6705   if (UnpckhSwapped)
6706     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6707
6708   llvm_unreachable("Unexpected result of UNPCK mask analysis");
6709   return SDValue();
6710 }
6711
6712 /// \brief Try to emit a bitmask instruction for a shuffle.
6713 ///
6714 /// This handles cases where we can model a blend exactly as a bitmask due to
6715 /// one of the inputs being zeroable.
6716 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6717                                            SDValue V2, ArrayRef<int> Mask,
6718                                            SelectionDAG &DAG) {
6719   MVT EltVT = VT.getScalarType();
6720   int NumEltBits = EltVT.getSizeInBits();
6721   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6722   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6723   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6724                                     IntEltVT);
6725   if (EltVT.isFloatingPoint()) {
6726     Zero = DAG.getBitcast(EltVT, Zero);
6727     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6728   }
6729   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6730   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6731   SDValue V;
6732   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6733     if (Zeroable[i])
6734       continue;
6735     if (Mask[i] % Size != i)
6736       return SDValue(); // Not a blend.
6737     if (!V)
6738       V = Mask[i] < Size ? V1 : V2;
6739     else if (V != (Mask[i] < Size ? V1 : V2))
6740       return SDValue(); // Can only let one input through the mask.
6741
6742     VMaskOps[i] = AllOnes;
6743   }
6744   if (!V)
6745     return SDValue(); // No non-zeroable elements!
6746
6747   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6748   V = DAG.getNode(VT.isFloatingPoint()
6749                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6750                   DL, VT, V, VMask);
6751   return V;
6752 }
6753
6754 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6755 ///
6756 /// This is used as a fallback approach when first class blend instructions are
6757 /// unavailable. Currently it is only suitable for integer vectors, but could
6758 /// be generalized for floating point vectors if desirable.
6759 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6760                                             SDValue V2, ArrayRef<int> Mask,
6761                                             SelectionDAG &DAG) {
6762   assert(VT.isInteger() && "Only supports integer vector types!");
6763   MVT EltVT = VT.getScalarType();
6764   int NumEltBits = EltVT.getSizeInBits();
6765   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6766   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6767                                     EltVT);
6768   SmallVector<SDValue, 16> MaskOps;
6769   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6770     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6771       return SDValue(); // Shuffled input!
6772     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6773   }
6774
6775   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6776   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6777   // We have to cast V2 around.
6778   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6779   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6780                                       DAG.getBitcast(MaskVT, V1Mask),
6781                                       DAG.getBitcast(MaskVT, V2)));
6782   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6783 }
6784
6785 /// \brief Try to emit a blend instruction for a shuffle.
6786 ///
6787 /// This doesn't do any checks for the availability of instructions for blending
6788 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6789 /// be matched in the backend with the type given. What it does check for is
6790 /// that the shuffle mask is in fact a blend.
6791 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6792                                          SDValue V2, ArrayRef<int> Mask,
6793                                          const X86Subtarget *Subtarget,
6794                                          SelectionDAG &DAG) {
6795   unsigned BlendMask = 0;
6796   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6797     if (Mask[i] >= Size) {
6798       if (Mask[i] != i + Size)
6799         return SDValue(); // Shuffled V2 input!
6800       BlendMask |= 1u << i;
6801       continue;
6802     }
6803     if (Mask[i] >= 0 && Mask[i] != i)
6804       return SDValue(); // Shuffled V1 input!
6805   }
6806   switch (VT.SimpleTy) {
6807   case MVT::v2f64:
6808   case MVT::v4f32:
6809   case MVT::v4f64:
6810   case MVT::v8f32:
6811     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6812                        DAG.getConstant(BlendMask, DL, MVT::i8));
6813
6814   case MVT::v4i64:
6815   case MVT::v8i32:
6816     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6817     // FALLTHROUGH
6818   case MVT::v2i64:
6819   case MVT::v4i32:
6820     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6821     // that instruction.
6822     if (Subtarget->hasAVX2()) {
6823       // Scale the blend by the number of 32-bit dwords per element.
6824       int Scale =  VT.getScalarSizeInBits() / 32;
6825       BlendMask = 0;
6826       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6827         if (Mask[i] >= Size)
6828           for (int j = 0; j < Scale; ++j)
6829             BlendMask |= 1u << (i * Scale + j);
6830
6831       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6832       V1 = DAG.getBitcast(BlendVT, V1);
6833       V2 = DAG.getBitcast(BlendVT, V2);
6834       return DAG.getBitcast(
6835           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6836                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6837     }
6838     // FALLTHROUGH
6839   case MVT::v8i16: {
6840     // For integer shuffles we need to expand the mask and cast the inputs to
6841     // v8i16s prior to blending.
6842     int Scale = 8 / VT.getVectorNumElements();
6843     BlendMask = 0;
6844     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6845       if (Mask[i] >= Size)
6846         for (int j = 0; j < Scale; ++j)
6847           BlendMask |= 1u << (i * Scale + j);
6848
6849     V1 = DAG.getBitcast(MVT::v8i16, V1);
6850     V2 = DAG.getBitcast(MVT::v8i16, V2);
6851     return DAG.getBitcast(VT,
6852                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6853                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6854   }
6855
6856   case MVT::v16i16: {
6857     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6858     SmallVector<int, 8> RepeatedMask;
6859     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6860       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6861       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6862       BlendMask = 0;
6863       for (int i = 0; i < 8; ++i)
6864         if (RepeatedMask[i] >= 16)
6865           BlendMask |= 1u << i;
6866       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6867                          DAG.getConstant(BlendMask, DL, MVT::i8));
6868     }
6869   }
6870     // FALLTHROUGH
6871   case MVT::v16i8:
6872   case MVT::v32i8: {
6873     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6874            "256-bit byte-blends require AVX2 support!");
6875
6876     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6877     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6878       return Masked;
6879
6880     // Scale the blend by the number of bytes per element.
6881     int Scale = VT.getScalarSizeInBits() / 8;
6882
6883     // This form of blend is always done on bytes. Compute the byte vector
6884     // type.
6885     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6886
6887     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6888     // mix of LLVM's code generator and the x86 backend. We tell the code
6889     // generator that boolean values in the elements of an x86 vector register
6890     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6891     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6892     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6893     // of the element (the remaining are ignored) and 0 in that high bit would
6894     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6895     // the LLVM model for boolean values in vector elements gets the relevant
6896     // bit set, it is set backwards and over constrained relative to x86's
6897     // actual model.
6898     SmallVector<SDValue, 32> VSELECTMask;
6899     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6900       for (int j = 0; j < Scale; ++j)
6901         VSELECTMask.push_back(
6902             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6903                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6904                                           MVT::i8));
6905
6906     V1 = DAG.getBitcast(BlendVT, V1);
6907     V2 = DAG.getBitcast(BlendVT, V2);
6908     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6909                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6910                                                       BlendVT, VSELECTMask),
6911                                           V1, V2));
6912   }
6913
6914   default:
6915     llvm_unreachable("Not a supported integer vector type!");
6916   }
6917 }
6918
6919 /// \brief Try to lower as a blend of elements from two inputs followed by
6920 /// a single-input permutation.
6921 ///
6922 /// This matches the pattern where we can blend elements from two inputs and
6923 /// then reduce the shuffle to a single-input permutation.
6924 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6925                                                    SDValue V2,
6926                                                    ArrayRef<int> Mask,
6927                                                    SelectionDAG &DAG) {
6928   // We build up the blend mask while checking whether a blend is a viable way
6929   // to reduce the shuffle.
6930   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6931   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6932
6933   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6934     if (Mask[i] < 0)
6935       continue;
6936
6937     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6938
6939     if (BlendMask[Mask[i] % Size] == -1)
6940       BlendMask[Mask[i] % Size] = Mask[i];
6941     else if (BlendMask[Mask[i] % Size] != Mask[i])
6942       return SDValue(); // Can't blend in the needed input!
6943
6944     PermuteMask[i] = Mask[i] % Size;
6945   }
6946
6947   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6948   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6949 }
6950
6951 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6952 /// blends and permutes.
6953 ///
6954 /// This matches the extremely common pattern for handling combined
6955 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6956 /// operations. It will try to pick the best arrangement of shuffles and
6957 /// blends.
6958 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6959                                                           SDValue V1,
6960                                                           SDValue V2,
6961                                                           ArrayRef<int> Mask,
6962                                                           SelectionDAG &DAG) {
6963   // Shuffle the input elements into the desired positions in V1 and V2 and
6964   // blend them together.
6965   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6966   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6967   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6968   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6969     if (Mask[i] >= 0 && Mask[i] < Size) {
6970       V1Mask[i] = Mask[i];
6971       BlendMask[i] = i;
6972     } else if (Mask[i] >= Size) {
6973       V2Mask[i] = Mask[i] - Size;
6974       BlendMask[i] = i + Size;
6975     }
6976
6977   // Try to lower with the simpler initial blend strategy unless one of the
6978   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6979   // shuffle may be able to fold with a load or other benefit. However, when
6980   // we'll have to do 2x as many shuffles in order to achieve this, blending
6981   // first is a better strategy.
6982   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6983     if (SDValue BlendPerm =
6984             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6985       return BlendPerm;
6986
6987   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6988   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6989   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6990 }
6991
6992 /// \brief Try to lower a vector shuffle as a byte rotation.
6993 ///
6994 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6995 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6996 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6997 /// try to generically lower a vector shuffle through such an pattern. It
6998 /// does not check for the profitability of lowering either as PALIGNR or
6999 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7000 /// This matches shuffle vectors that look like:
7001 ///
7002 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7003 ///
7004 /// Essentially it concatenates V1 and V2, shifts right by some number of
7005 /// elements, and takes the low elements as the result. Note that while this is
7006 /// specified as a *right shift* because x86 is little-endian, it is a *left
7007 /// rotate* of the vector lanes.
7008 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7009                                               SDValue V2,
7010                                               ArrayRef<int> Mask,
7011                                               const X86Subtarget *Subtarget,
7012                                               SelectionDAG &DAG) {
7013   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7014
7015   int NumElts = Mask.size();
7016   int NumLanes = VT.getSizeInBits() / 128;
7017   int NumLaneElts = NumElts / NumLanes;
7018
7019   // We need to detect various ways of spelling a rotation:
7020   //   [11, 12, 13, 14, 15,  0,  1,  2]
7021   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7022   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7023   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7024   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7025   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7026   int Rotation = 0;
7027   SDValue Lo, Hi;
7028   for (int l = 0; l < NumElts; l += NumLaneElts) {
7029     for (int i = 0; i < NumLaneElts; ++i) {
7030       if (Mask[l + i] == -1)
7031         continue;
7032       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7033
7034       // Get the mod-Size index and lane correct it.
7035       int LaneIdx = (Mask[l + i] % NumElts) - l;
7036       // Make sure it was in this lane.
7037       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7038         return SDValue();
7039
7040       // Determine where a rotated vector would have started.
7041       int StartIdx = i - LaneIdx;
7042       if (StartIdx == 0)
7043         // The identity rotation isn't interesting, stop.
7044         return SDValue();
7045
7046       // If we found the tail of a vector the rotation must be the missing
7047       // front. If we found the head of a vector, it must be how much of the
7048       // head.
7049       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7050
7051       if (Rotation == 0)
7052         Rotation = CandidateRotation;
7053       else if (Rotation != CandidateRotation)
7054         // The rotations don't match, so we can't match this mask.
7055         return SDValue();
7056
7057       // Compute which value this mask is pointing at.
7058       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7059
7060       // Compute which of the two target values this index should be assigned
7061       // to. This reflects whether the high elements are remaining or the low
7062       // elements are remaining.
7063       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7064
7065       // Either set up this value if we've not encountered it before, or check
7066       // that it remains consistent.
7067       if (!TargetV)
7068         TargetV = MaskV;
7069       else if (TargetV != MaskV)
7070         // This may be a rotation, but it pulls from the inputs in some
7071         // unsupported interleaving.
7072         return SDValue();
7073     }
7074   }
7075
7076   // Check that we successfully analyzed the mask, and normalize the results.
7077   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7078   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7079   if (!Lo)
7080     Lo = Hi;
7081   else if (!Hi)
7082     Hi = Lo;
7083
7084   // The actual rotate instruction rotates bytes, so we need to scale the
7085   // rotation based on how many bytes are in the vector lane.
7086   int Scale = 16 / NumLaneElts;
7087
7088   // SSSE3 targets can use the palignr instruction.
7089   if (Subtarget->hasSSSE3()) {
7090     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7091     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7092     Lo = DAG.getBitcast(AlignVT, Lo);
7093     Hi = DAG.getBitcast(AlignVT, Hi);
7094
7095     return DAG.getBitcast(
7096         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7097                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7098   }
7099
7100   assert(VT.getSizeInBits() == 128 &&
7101          "Rotate-based lowering only supports 128-bit lowering!");
7102   assert(Mask.size() <= 16 &&
7103          "Can shuffle at most 16 bytes in a 128-bit vector!");
7104
7105   // Default SSE2 implementation
7106   int LoByteShift = 16 - Rotation * Scale;
7107   int HiByteShift = Rotation * Scale;
7108
7109   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7110   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7111   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7112
7113   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7114                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7115   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7116                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7117   return DAG.getBitcast(VT,
7118                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7119 }
7120
7121 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7122 ///
7123 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7124 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7125 /// matches elements from one of the input vectors shuffled to the left or
7126 /// right with zeroable elements 'shifted in'. It handles both the strictly
7127 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7128 /// quad word lane.
7129 ///
7130 /// PSHL : (little-endian) left bit shift.
7131 /// [ zz, 0, zz,  2 ]
7132 /// [ -1, 4, zz, -1 ]
7133 /// PSRL : (little-endian) right bit shift.
7134 /// [  1, zz,  3, zz]
7135 /// [ -1, -1,  7, zz]
7136 /// PSLLDQ : (little-endian) left byte shift
7137 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7138 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7139 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7140 /// PSRLDQ : (little-endian) right byte shift
7141 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7142 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7143 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7144 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7145                                          SDValue V2, ArrayRef<int> Mask,
7146                                          SelectionDAG &DAG) {
7147   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7148
7149   int Size = Mask.size();
7150   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7151
7152   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7153     for (int i = 0; i < Size; i += Scale)
7154       for (int j = 0; j < Shift; ++j)
7155         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7156           return false;
7157
7158     return true;
7159   };
7160
7161   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7162     for (int i = 0; i != Size; i += Scale) {
7163       unsigned Pos = Left ? i + Shift : i;
7164       unsigned Low = Left ? i : i + Shift;
7165       unsigned Len = Scale - Shift;
7166       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7167                                       Low + (V == V1 ? 0 : Size)))
7168         return SDValue();
7169     }
7170
7171     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7172     bool ByteShift = ShiftEltBits > 64;
7173     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7174                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7175     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7176
7177     // Normalize the scale for byte shifts to still produce an i64 element
7178     // type.
7179     Scale = ByteShift ? Scale / 2 : Scale;
7180
7181     // We need to round trip through the appropriate type for the shift.
7182     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7183     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7184     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7185            "Illegal integer vector type");
7186     V = DAG.getBitcast(ShiftVT, V);
7187
7188     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7189                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7190     return DAG.getBitcast(VT, V);
7191   };
7192
7193   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7194   // keep doubling the size of the integer elements up to that. We can
7195   // then shift the elements of the integer vector by whole multiples of
7196   // their width within the elements of the larger integer vector. Test each
7197   // multiple to see if we can find a match with the moved element indices
7198   // and that the shifted in elements are all zeroable.
7199   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7200     for (int Shift = 1; Shift != Scale; ++Shift)
7201       for (bool Left : {true, false})
7202         if (CheckZeros(Shift, Scale, Left))
7203           for (SDValue V : {V1, V2})
7204             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7205               return Match;
7206
7207   // no match
7208   return SDValue();
7209 }
7210
7211 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7212 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7213                                            SDValue V2, ArrayRef<int> Mask,
7214                                            SelectionDAG &DAG) {
7215   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7216   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7217
7218   int Size = Mask.size();
7219   int HalfSize = Size / 2;
7220   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7221
7222   // Upper half must be undefined.
7223   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7224     return SDValue();
7225
7226   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7227   // Remainder of lower half result is zero and upper half is all undef.
7228   auto LowerAsEXTRQ = [&]() {
7229     // Determine the extraction length from the part of the
7230     // lower half that isn't zeroable.
7231     int Len = HalfSize;
7232     for (; Len >= 0; --Len)
7233       if (!Zeroable[Len - 1])
7234         break;
7235     assert(Len > 0 && "Zeroable shuffle mask");
7236
7237     // Attempt to match first Len sequential elements from the lower half.
7238     SDValue Src;
7239     int Idx = -1;
7240     for (int i = 0; i != Len; ++i) {
7241       int M = Mask[i];
7242       if (M < 0)
7243         continue;
7244       SDValue &V = (M < Size ? V1 : V2);
7245       M = M % Size;
7246
7247       // All mask elements must be in the lower half.
7248       if (M > HalfSize)
7249         return SDValue();
7250
7251       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7252         Src = V;
7253         Idx = M - i;
7254         continue;
7255       }
7256       return SDValue();
7257     }
7258
7259     if (Idx < 0)
7260       return SDValue();
7261
7262     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7263     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7264     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7265     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7266                        DAG.getConstant(BitLen, DL, MVT::i8),
7267                        DAG.getConstant(BitIdx, DL, MVT::i8));
7268   };
7269
7270   if (SDValue ExtrQ = LowerAsEXTRQ())
7271     return ExtrQ;
7272
7273   // INSERTQ: Extract lowest Len elements from lower half of second source and
7274   // insert over first source, starting at Idx.
7275   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7276   auto LowerAsInsertQ = [&]() {
7277     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7278       SDValue Base;
7279
7280       // Attempt to match first source from mask before insertion point.
7281       if (isUndefInRange(Mask, 0, Idx)) {
7282         /* EMPTY */
7283       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7284         Base = V1;
7285       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7286         Base = V2;
7287       } else {
7288         continue;
7289       }
7290
7291       // Extend the extraction length looking to match both the insertion of
7292       // the second source and the remaining elements of the first.
7293       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7294         SDValue Insert;
7295         int Len = Hi - Idx;
7296
7297         // Match insertion.
7298         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7299           Insert = V1;
7300         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7301           Insert = V2;
7302         } else {
7303           continue;
7304         }
7305
7306         // Match the remaining elements of the lower half.
7307         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7308           /* EMPTY */
7309         } else if ((!Base || (Base == V1)) &&
7310                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7311           Base = V1;
7312         } else if ((!Base || (Base == V2)) &&
7313                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7314                                               Size + Hi)) {
7315           Base = V2;
7316         } else {
7317           continue;
7318         }
7319
7320         // We may not have a base (first source) - this can safely be undefined.
7321         if (!Base)
7322           Base = DAG.getUNDEF(VT);
7323
7324         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7325         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7326         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7327                            DAG.getConstant(BitLen, DL, MVT::i8),
7328                            DAG.getConstant(BitIdx, DL, MVT::i8));
7329       }
7330     }
7331
7332     return SDValue();
7333   };
7334
7335   if (SDValue InsertQ = LowerAsInsertQ())
7336     return InsertQ;
7337
7338   return SDValue();
7339 }
7340
7341 /// \brief Lower a vector shuffle as a zero or any extension.
7342 ///
7343 /// Given a specific number of elements, element bit width, and extension
7344 /// stride, produce either a zero or any extension based on the available
7345 /// features of the subtarget. The extended elements are consecutive and
7346 /// begin and can start from an offseted element index in the input; to
7347 /// avoid excess shuffling the offset must either being in the bottom lane
7348 /// or at the start of a higher lane. All extended elements must be from
7349 /// the same lane.
7350 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7351     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7352     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7353   assert(Scale > 1 && "Need a scale to extend.");
7354   int EltBits = VT.getScalarSizeInBits();
7355   int NumElements = VT.getVectorNumElements();
7356   int NumEltsPerLane = 128 / EltBits;
7357   int OffsetLane = Offset / NumEltsPerLane;
7358   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7359          "Only 8, 16, and 32 bit elements can be extended.");
7360   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7361   assert(0 <= Offset && "Extension offset must be positive.");
7362   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7363          "Extension offset must be in the first lane or start an upper lane.");
7364
7365   // Check that an index is in same lane as the base offset.
7366   auto SafeOffset = [&](int Idx) {
7367     return OffsetLane == (Idx / NumEltsPerLane);
7368   };
7369
7370   // Shift along an input so that the offset base moves to the first element.
7371   auto ShuffleOffset = [&](SDValue V) {
7372     if (!Offset)
7373       return V;
7374
7375     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7376     for (int i = 0; i * Scale < NumElements; ++i) {
7377       int SrcIdx = i + Offset;
7378       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7379     }
7380     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7381   };
7382
7383   // Found a valid zext mask! Try various lowering strategies based on the
7384   // input type and available ISA extensions.
7385   if (Subtarget->hasSSE41()) {
7386     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7387     // PUNPCK will catch this in a later shuffle match.
7388     if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7389       return SDValue();
7390     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7391                                  NumElements / Scale);
7392     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7393     return DAG.getBitcast(VT, InputV);
7394   }
7395
7396   assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7397
7398   // For any extends we can cheat for larger element sizes and use shuffle
7399   // instructions that can fold with a load and/or copy.
7400   if (AnyExt && EltBits == 32) {
7401     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7402                          -1};
7403     return DAG.getBitcast(
7404         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7405                         DAG.getBitcast(MVT::v4i32, InputV),
7406                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7407   }
7408   if (AnyExt && EltBits == 16 && Scale > 2) {
7409     int PSHUFDMask[4] = {Offset / 2, -1,
7410                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7411     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7412                          DAG.getBitcast(MVT::v4i32, InputV),
7413                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7414     int PSHUFWMask[4] = {1, -1, -1, -1};
7415     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7416     return DAG.getBitcast(
7417         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7418                         DAG.getBitcast(MVT::v8i16, InputV),
7419                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7420   }
7421
7422   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7423   // to 64-bits.
7424   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7425     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7426     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7427
7428     int LoIdx = Offset * EltBits;
7429     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7430                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7431                                          DAG.getConstant(EltBits, DL, MVT::i8),
7432                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7433
7434     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7435         !SafeOffset(Offset + 1))
7436       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7437
7438     int HiIdx = (Offset + 1) * EltBits;
7439     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7440                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7441                                          DAG.getConstant(EltBits, DL, MVT::i8),
7442                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7443     return DAG.getNode(ISD::BITCAST, DL, VT,
7444                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7445   }
7446
7447   // If this would require more than 2 unpack instructions to expand, use
7448   // pshufb when available. We can only use more than 2 unpack instructions
7449   // when zero extending i8 elements which also makes it easier to use pshufb.
7450   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7451     assert(NumElements == 16 && "Unexpected byte vector width!");
7452     SDValue PSHUFBMask[16];
7453     for (int i = 0; i < 16; ++i) {
7454       int Idx = Offset + (i / Scale);
7455       PSHUFBMask[i] = DAG.getConstant(
7456           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7457     }
7458     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7459     return DAG.getBitcast(VT,
7460                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7461                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7462                                                   MVT::v16i8, PSHUFBMask)));
7463   }
7464
7465   // If we are extending from an (odd)offset, shuffle them by 1 element.
7466   if (Offset & 1) {
7467     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7468     for (int i = 1; i < NumElements; ++i)
7469       ShMask[i - 1] = i;
7470     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7471     Offset--;
7472   }
7473
7474   // Otherwise emit a sequence of unpacks.
7475   do {
7476     unsigned UnpackLoHi = X86ISD::UNPCKL;
7477     if (Offset >= (NumElements / 2)) {
7478       UnpackLoHi = X86ISD::UNPCKH;
7479       Offset -= (NumElements / 2);
7480     }
7481
7482     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7483     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7484                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7485     InputV = DAG.getBitcast(InputVT, InputV);
7486     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7487     Scale /= 2;
7488     EltBits *= 2;
7489     NumElements /= 2;
7490   } while (Scale > 1);
7491   return DAG.getBitcast(VT, InputV);
7492 }
7493
7494 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7495 ///
7496 /// This routine will try to do everything in its power to cleverly lower
7497 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7498 /// check for the profitability of this lowering,  it tries to aggressively
7499 /// match this pattern. It will use all of the micro-architectural details it
7500 /// can to emit an efficient lowering. It handles both blends with all-zero
7501 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7502 /// masking out later).
7503 ///
7504 /// The reason we have dedicated lowering for zext-style shuffles is that they
7505 /// are both incredibly common and often quite performance sensitive.
7506 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7507     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7508     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7509   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7510
7511   int Bits = VT.getSizeInBits();
7512   int NumLanes = Bits / 128;
7513   int NumElements = VT.getVectorNumElements();
7514   int NumEltsPerLane = NumElements / NumLanes;
7515   assert(VT.getScalarSizeInBits() <= 32 &&
7516          "Exceeds 32-bit integer zero extension limit");
7517   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7518
7519   // Define a helper function to check a particular ext-scale and lower to it if
7520   // valid.
7521   auto Lower = [&](int Scale) -> SDValue {
7522     SDValue InputV;
7523     bool AnyExt = true;
7524     int Offset = 0;
7525     int Matches = 0;
7526     for (int i = 0; i < NumElements; ++i) {
7527       int M = Mask[i];
7528       if (M == -1)
7529         continue; // Valid anywhere but doesn't tell us anything.
7530       if (i % Scale != 0) {
7531         // Each of the extended elements need to be zeroable.
7532         if (!Zeroable[i])
7533           return SDValue();
7534
7535         // We no longer are in the anyext case.
7536         AnyExt = false;
7537         continue;
7538       }
7539
7540       // Each of the base elements needs to be consecutive indices into the
7541       // same input vector.
7542       SDValue V = M < NumElements ? V1 : V2;
7543       M = M % NumElements;
7544       if (!InputV) {
7545         InputV = V;
7546         Offset = M - (i / Scale);
7547       } else if (InputV != V)
7548         return SDValue(); // Flip-flopping inputs.
7549
7550       // Offset must start in the lowest 128-bit lane or at the start of an
7551       // upper lane.
7552       // FIXME: Is it ever worth allowing a negative base offset?
7553       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7554             (Offset % NumEltsPerLane) == 0))
7555         return SDValue();
7556
7557       // If we are offsetting, all referenced entries must come from the same
7558       // lane.
7559       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7560         return SDValue();
7561
7562       if ((M % NumElements) != (Offset + (i / Scale)))
7563         return SDValue(); // Non-consecutive strided elements.
7564       Matches++;
7565     }
7566
7567     // If we fail to find an input, we have a zero-shuffle which should always
7568     // have already been handled.
7569     // FIXME: Maybe handle this here in case during blending we end up with one?
7570     if (!InputV)
7571       return SDValue();
7572
7573     // If we are offsetting, don't extend if we only match a single input, we
7574     // can always do better by using a basic PSHUF or PUNPCK.
7575     if (Offset != 0 && Matches < 2)
7576       return SDValue();
7577
7578     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7579         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7580   };
7581
7582   // The widest scale possible for extending is to a 64-bit integer.
7583   assert(Bits % 64 == 0 &&
7584          "The number of bits in a vector must be divisible by 64 on x86!");
7585   int NumExtElements = Bits / 64;
7586
7587   // Each iteration, try extending the elements half as much, but into twice as
7588   // many elements.
7589   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7590     assert(NumElements % NumExtElements == 0 &&
7591            "The input vector size must be divisible by the extended size.");
7592     if (SDValue V = Lower(NumElements / NumExtElements))
7593       return V;
7594   }
7595
7596   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7597   if (Bits != 128)
7598     return SDValue();
7599
7600   // Returns one of the source operands if the shuffle can be reduced to a
7601   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7602   auto CanZExtLowHalf = [&]() {
7603     for (int i = NumElements / 2; i != NumElements; ++i)
7604       if (!Zeroable[i])
7605         return SDValue();
7606     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7607       return V1;
7608     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7609       return V2;
7610     return SDValue();
7611   };
7612
7613   if (SDValue V = CanZExtLowHalf()) {
7614     V = DAG.getBitcast(MVT::v2i64, V);
7615     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7616     return DAG.getBitcast(VT, V);
7617   }
7618
7619   // No viable ext lowering found.
7620   return SDValue();
7621 }
7622
7623 /// \brief Try to get a scalar value for a specific element of a vector.
7624 ///
7625 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7626 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7627                                               SelectionDAG &DAG) {
7628   MVT VT = V.getSimpleValueType();
7629   MVT EltVT = VT.getVectorElementType();
7630   while (V.getOpcode() == ISD::BITCAST)
7631     V = V.getOperand(0);
7632   // If the bitcasts shift the element size, we can't extract an equivalent
7633   // element from it.
7634   MVT NewVT = V.getSimpleValueType();
7635   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7636     return SDValue();
7637
7638   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7639       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7640     // Ensure the scalar operand is the same size as the destination.
7641     // FIXME: Add support for scalar truncation where possible.
7642     SDValue S = V.getOperand(Idx);
7643     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7644       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7645   }
7646
7647   return SDValue();
7648 }
7649
7650 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7651 ///
7652 /// This is particularly important because the set of instructions varies
7653 /// significantly based on whether the operand is a load or not.
7654 static bool isShuffleFoldableLoad(SDValue V) {
7655   while (V.getOpcode() == ISD::BITCAST)
7656     V = V.getOperand(0);
7657
7658   return ISD::isNON_EXTLoad(V.getNode());
7659 }
7660
7661 /// \brief Try to lower insertion of a single element into a zero vector.
7662 ///
7663 /// This is a common pattern that we have especially efficient patterns to lower
7664 /// across all subtarget feature sets.
7665 static SDValue lowerVectorShuffleAsElementInsertion(
7666     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7667     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7668   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7669   MVT ExtVT = VT;
7670   MVT EltVT = VT.getVectorElementType();
7671
7672   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7673                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7674                 Mask.begin();
7675   bool IsV1Zeroable = true;
7676   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7677     if (i != V2Index && !Zeroable[i]) {
7678       IsV1Zeroable = false;
7679       break;
7680     }
7681
7682   // Check for a single input from a SCALAR_TO_VECTOR node.
7683   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7684   // all the smarts here sunk into that routine. However, the current
7685   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7686   // vector shuffle lowering is dead.
7687   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7688                                                DAG);
7689   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7690     // We need to zext the scalar if it is smaller than an i32.
7691     V2S = DAG.getBitcast(EltVT, V2S);
7692     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7693       // Using zext to expand a narrow element won't work for non-zero
7694       // insertions.
7695       if (!IsV1Zeroable)
7696         return SDValue();
7697
7698       // Zero-extend directly to i32.
7699       ExtVT = MVT::v4i32;
7700       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7701     }
7702     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7703   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7704              EltVT == MVT::i16) {
7705     // Either not inserting from the low element of the input or the input
7706     // element size is too small to use VZEXT_MOVL to clear the high bits.
7707     return SDValue();
7708   }
7709
7710   if (!IsV1Zeroable) {
7711     // If V1 can't be treated as a zero vector we have fewer options to lower
7712     // this. We can't support integer vectors or non-zero targets cheaply, and
7713     // the V1 elements can't be permuted in any way.
7714     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7715     if (!VT.isFloatingPoint() || V2Index != 0)
7716       return SDValue();
7717     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7718     V1Mask[V2Index] = -1;
7719     if (!isNoopShuffleMask(V1Mask))
7720       return SDValue();
7721     // This is essentially a special case blend operation, but if we have
7722     // general purpose blend operations, they are always faster. Bail and let
7723     // the rest of the lowering handle these as blends.
7724     if (Subtarget->hasSSE41())
7725       return SDValue();
7726
7727     // Otherwise, use MOVSD or MOVSS.
7728     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7729            "Only two types of floating point element types to handle!");
7730     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7731                        ExtVT, V1, V2);
7732   }
7733
7734   // This lowering only works for the low element with floating point vectors.
7735   if (VT.isFloatingPoint() && V2Index != 0)
7736     return SDValue();
7737
7738   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7739   if (ExtVT != VT)
7740     V2 = DAG.getBitcast(VT, V2);
7741
7742   if (V2Index != 0) {
7743     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7744     // the desired position. Otherwise it is more efficient to do a vector
7745     // shift left. We know that we can do a vector shift left because all
7746     // the inputs are zero.
7747     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7748       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7749       V2Shuffle[V2Index] = 0;
7750       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7751     } else {
7752       V2 = DAG.getBitcast(MVT::v2i64, V2);
7753       V2 = DAG.getNode(
7754           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7755           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7756                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7757                               DAG.getDataLayout(), VT)));
7758       V2 = DAG.getBitcast(VT, V2);
7759     }
7760   }
7761   return V2;
7762 }
7763
7764 /// \brief Try to lower broadcast of a single element.
7765 ///
7766 /// For convenience, this code also bundles all of the subtarget feature set
7767 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7768 /// a convenient way to factor it out.
7769 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7770                                              ArrayRef<int> Mask,
7771                                              const X86Subtarget *Subtarget,
7772                                              SelectionDAG &DAG) {
7773   if (!Subtarget->hasAVX())
7774     return SDValue();
7775   if (VT.isInteger() && !Subtarget->hasAVX2())
7776     return SDValue();
7777
7778   // Check that the mask is a broadcast.
7779   int BroadcastIdx = -1;
7780   for (int M : Mask)
7781     if (M >= 0 && BroadcastIdx == -1)
7782       BroadcastIdx = M;
7783     else if (M >= 0 && M != BroadcastIdx)
7784       return SDValue();
7785
7786   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7787                                             "a sorted mask where the broadcast "
7788                                             "comes from V1.");
7789
7790   // Go up the chain of (vector) values to find a scalar load that we can
7791   // combine with the broadcast.
7792   for (;;) {
7793     switch (V.getOpcode()) {
7794     case ISD::CONCAT_VECTORS: {
7795       int OperandSize = Mask.size() / V.getNumOperands();
7796       V = V.getOperand(BroadcastIdx / OperandSize);
7797       BroadcastIdx %= OperandSize;
7798       continue;
7799     }
7800
7801     case ISD::INSERT_SUBVECTOR: {
7802       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7803       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7804       if (!ConstantIdx)
7805         break;
7806
7807       int BeginIdx = (int)ConstantIdx->getZExtValue();
7808       int EndIdx =
7809           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7810       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7811         BroadcastIdx -= BeginIdx;
7812         V = VInner;
7813       } else {
7814         V = VOuter;
7815       }
7816       continue;
7817     }
7818     }
7819     break;
7820   }
7821
7822   // Check if this is a broadcast of a scalar. We special case lowering
7823   // for scalars so that we can more effectively fold with loads.
7824   // First, look through bitcast: if the original value has a larger element
7825   // type than the shuffle, the broadcast element is in essence truncated.
7826   // Make that explicit to ease folding.
7827   if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7828     EVT EltVT = VT.getVectorElementType();
7829     SDValue V0 = V.getOperand(0);
7830     EVT V0VT = V0.getValueType();
7831
7832     if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7833         ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7834          (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7835       V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7836       BroadcastIdx = 0;
7837     }
7838   }
7839
7840   // Also check the simpler case, where we can directly reuse the scalar.
7841   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7842       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7843     V = V.getOperand(BroadcastIdx);
7844
7845     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7846     // Only AVX2 has register broadcasts.
7847     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7848       return SDValue();
7849   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7850     // We can't broadcast from a vector register without AVX2, and we can only
7851     // broadcast from the zero-element of a vector register.
7852     return SDValue();
7853   }
7854
7855   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7856 }
7857
7858 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7859 // INSERTPS when the V1 elements are already in the correct locations
7860 // because otherwise we can just always use two SHUFPS instructions which
7861 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7862 // perform INSERTPS if a single V1 element is out of place and all V2
7863 // elements are zeroable.
7864 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7865                                             ArrayRef<int> Mask,
7866                                             SelectionDAG &DAG) {
7867   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7868   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7869   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7870   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7871
7872   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7873
7874   unsigned ZMask = 0;
7875   int V1DstIndex = -1;
7876   int V2DstIndex = -1;
7877   bool V1UsedInPlace = false;
7878
7879   for (int i = 0; i < 4; ++i) {
7880     // Synthesize a zero mask from the zeroable elements (includes undefs).
7881     if (Zeroable[i]) {
7882       ZMask |= 1 << i;
7883       continue;
7884     }
7885
7886     // Flag if we use any V1 inputs in place.
7887     if (i == Mask[i]) {
7888       V1UsedInPlace = true;
7889       continue;
7890     }
7891
7892     // We can only insert a single non-zeroable element.
7893     if (V1DstIndex != -1 || V2DstIndex != -1)
7894       return SDValue();
7895
7896     if (Mask[i] < 4) {
7897       // V1 input out of place for insertion.
7898       V1DstIndex = i;
7899     } else {
7900       // V2 input for insertion.
7901       V2DstIndex = i;
7902     }
7903   }
7904
7905   // Don't bother if we have no (non-zeroable) element for insertion.
7906   if (V1DstIndex == -1 && V2DstIndex == -1)
7907     return SDValue();
7908
7909   // Determine element insertion src/dst indices. The src index is from the
7910   // start of the inserted vector, not the start of the concatenated vector.
7911   unsigned V2SrcIndex = 0;
7912   if (V1DstIndex != -1) {
7913     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7914     // and don't use the original V2 at all.
7915     V2SrcIndex = Mask[V1DstIndex];
7916     V2DstIndex = V1DstIndex;
7917     V2 = V1;
7918   } else {
7919     V2SrcIndex = Mask[V2DstIndex] - 4;
7920   }
7921
7922   // If no V1 inputs are used in place, then the result is created only from
7923   // the zero mask and the V2 insertion - so remove V1 dependency.
7924   if (!V1UsedInPlace)
7925     V1 = DAG.getUNDEF(MVT::v4f32);
7926
7927   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7928   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7929
7930   // Insert the V2 element into the desired position.
7931   SDLoc DL(Op);
7932   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7933                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7934 }
7935
7936 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7937 /// UNPCK instruction.
7938 ///
7939 /// This specifically targets cases where we end up with alternating between
7940 /// the two inputs, and so can permute them into something that feeds a single
7941 /// UNPCK instruction. Note that this routine only targets integer vectors
7942 /// because for floating point vectors we have a generalized SHUFPS lowering
7943 /// strategy that handles everything that doesn't *exactly* match an unpack,
7944 /// making this clever lowering unnecessary.
7945 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7946                                                     SDValue V1, SDValue V2,
7947                                                     ArrayRef<int> Mask,
7948                                                     SelectionDAG &DAG) {
7949   assert(!VT.isFloatingPoint() &&
7950          "This routine only supports integer vectors.");
7951   assert(!isSingleInputShuffleMask(Mask) &&
7952          "This routine should only be used when blending two inputs.");
7953   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7954
7955   int Size = Mask.size();
7956
7957   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7958     return M >= 0 && M % Size < Size / 2;
7959   });
7960   int NumHiInputs = std::count_if(
7961       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7962
7963   bool UnpackLo = NumLoInputs >= NumHiInputs;
7964
7965   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7966     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7967     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7968
7969     for (int i = 0; i < Size; ++i) {
7970       if (Mask[i] < 0)
7971         continue;
7972
7973       // Each element of the unpack contains Scale elements from this mask.
7974       int UnpackIdx = i / Scale;
7975
7976       // We only handle the case where V1 feeds the first slots of the unpack.
7977       // We rely on canonicalization to ensure this is the case.
7978       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7979         return SDValue();
7980
7981       // Setup the mask for this input. The indexing is tricky as we have to
7982       // handle the unpack stride.
7983       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7984       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7985           Mask[i] % Size;
7986     }
7987
7988     // If we will have to shuffle both inputs to use the unpack, check whether
7989     // we can just unpack first and shuffle the result. If so, skip this unpack.
7990     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7991         !isNoopShuffleMask(V2Mask))
7992       return SDValue();
7993
7994     // Shuffle the inputs into place.
7995     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7996     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7997
7998     // Cast the inputs to the type we will use to unpack them.
7999     V1 = DAG.getBitcast(UnpackVT, V1);
8000     V2 = DAG.getBitcast(UnpackVT, V2);
8001
8002     // Unpack the inputs and cast the result back to the desired type.
8003     return DAG.getBitcast(
8004         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8005                         UnpackVT, V1, V2));
8006   };
8007
8008   // We try each unpack from the largest to the smallest to try and find one
8009   // that fits this mask.
8010   int OrigNumElements = VT.getVectorNumElements();
8011   int OrigScalarSize = VT.getScalarSizeInBits();
8012   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8013     int Scale = ScalarSize / OrigScalarSize;
8014     int NumElements = OrigNumElements / Scale;
8015     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8016     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8017       return Unpack;
8018   }
8019
8020   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8021   // initial unpack.
8022   if (NumLoInputs == 0 || NumHiInputs == 0) {
8023     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8024            "We have to have *some* inputs!");
8025     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8026
8027     // FIXME: We could consider the total complexity of the permute of each
8028     // possible unpacking. Or at the least we should consider how many
8029     // half-crossings are created.
8030     // FIXME: We could consider commuting the unpacks.
8031
8032     SmallVector<int, 32> PermMask;
8033     PermMask.assign(Size, -1);
8034     for (int i = 0; i < Size; ++i) {
8035       if (Mask[i] < 0)
8036         continue;
8037
8038       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8039
8040       PermMask[i] =
8041           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8042     }
8043     return DAG.getVectorShuffle(
8044         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8045                             DL, VT, V1, V2),
8046         DAG.getUNDEF(VT), PermMask);
8047   }
8048
8049   return SDValue();
8050 }
8051
8052 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8053 ///
8054 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8055 /// support for floating point shuffles but not integer shuffles. These
8056 /// instructions will incur a domain crossing penalty on some chips though so
8057 /// it is better to avoid lowering through this for integer vectors where
8058 /// possible.
8059 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8060                                        const X86Subtarget *Subtarget,
8061                                        SelectionDAG &DAG) {
8062   SDLoc DL(Op);
8063   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8064   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8065   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8066   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8067   ArrayRef<int> Mask = SVOp->getMask();
8068   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8069
8070   if (isSingleInputShuffleMask(Mask)) {
8071     // Use low duplicate instructions for masks that match their pattern.
8072     if (Subtarget->hasSSE3())
8073       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8074         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8075
8076     // Straight shuffle of a single input vector. Simulate this by using the
8077     // single input as both of the "inputs" to this instruction..
8078     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8079
8080     if (Subtarget->hasAVX()) {
8081       // If we have AVX, we can use VPERMILPS which will allow folding a load
8082       // into the shuffle.
8083       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8084                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8085     }
8086
8087     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8088                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8089   }
8090   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8091   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8092
8093   // If we have a single input, insert that into V1 if we can do so cheaply.
8094   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8095     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8096             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8097       return Insertion;
8098     // Try inverting the insertion since for v2 masks it is easy to do and we
8099     // can't reliably sort the mask one way or the other.
8100     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8101                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8102     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8103             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8104       return Insertion;
8105   }
8106
8107   // Try to use one of the special instruction patterns to handle two common
8108   // blend patterns if a zero-blend above didn't work.
8109   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8110       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8111     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8112       // We can either use a special instruction to load over the low double or
8113       // to move just the low double.
8114       return DAG.getNode(
8115           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8116           DL, MVT::v2f64, V2,
8117           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8118
8119   if (Subtarget->hasSSE41())
8120     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8121                                                   Subtarget, DAG))
8122       return Blend;
8123
8124   // Use dedicated unpack instructions for masks that match their pattern.
8125   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8126     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8127   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8128     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8129
8130   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8131   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8132                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8133 }
8134
8135 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8136 ///
8137 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8138 /// the integer unit to minimize domain crossing penalties. However, for blends
8139 /// it falls back to the floating point shuffle operation with appropriate bit
8140 /// casting.
8141 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8142                                        const X86Subtarget *Subtarget,
8143                                        SelectionDAG &DAG) {
8144   SDLoc DL(Op);
8145   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8146   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8147   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8148   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8149   ArrayRef<int> Mask = SVOp->getMask();
8150   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8151
8152   if (isSingleInputShuffleMask(Mask)) {
8153     // Check for being able to broadcast a single element.
8154     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8155                                                           Mask, Subtarget, DAG))
8156       return Broadcast;
8157
8158     // Straight shuffle of a single input vector. For everything from SSE2
8159     // onward this has a single fast instruction with no scary immediates.
8160     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8161     V1 = DAG.getBitcast(MVT::v4i32, V1);
8162     int WidenedMask[4] = {
8163         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8164         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8165     return DAG.getBitcast(
8166         MVT::v2i64,
8167         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8168                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8169   }
8170   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8171   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8172   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8173   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8174
8175   // If we have a blend of two PACKUS operations an the blend aligns with the
8176   // low and half halves, we can just merge the PACKUS operations. This is
8177   // particularly important as it lets us merge shuffles that this routine itself
8178   // creates.
8179   auto GetPackNode = [](SDValue V) {
8180     while (V.getOpcode() == ISD::BITCAST)
8181       V = V.getOperand(0);
8182
8183     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8184   };
8185   if (SDValue V1Pack = GetPackNode(V1))
8186     if (SDValue V2Pack = GetPackNode(V2))
8187       return DAG.getBitcast(MVT::v2i64,
8188                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8189                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8190                                                      : V1Pack.getOperand(1),
8191                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8192                                                      : V2Pack.getOperand(1)));
8193
8194   // Try to use shift instructions.
8195   if (SDValue Shift =
8196           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8197     return Shift;
8198
8199   // When loading a scalar and then shuffling it into a vector we can often do
8200   // the insertion cheaply.
8201   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8202           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8203     return Insertion;
8204   // Try inverting the insertion since for v2 masks it is easy to do and we
8205   // can't reliably sort the mask one way or the other.
8206   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8207   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8208           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8209     return Insertion;
8210
8211   // We have different paths for blend lowering, but they all must use the
8212   // *exact* same predicate.
8213   bool IsBlendSupported = Subtarget->hasSSE41();
8214   if (IsBlendSupported)
8215     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8216                                                   Subtarget, DAG))
8217       return Blend;
8218
8219   // Use dedicated unpack instructions for masks that match their pattern.
8220   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8221     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8222   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8223     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8224
8225   // Try to use byte rotation instructions.
8226   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8227   if (Subtarget->hasSSSE3())
8228     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8229             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8230       return Rotate;
8231
8232   // If we have direct support for blends, we should lower by decomposing into
8233   // a permute. That will be faster than the domain cross.
8234   if (IsBlendSupported)
8235     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8236                                                       Mask, DAG);
8237
8238   // We implement this with SHUFPD which is pretty lame because it will likely
8239   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8240   // However, all the alternatives are still more cycles and newer chips don't
8241   // have this problem. It would be really nice if x86 had better shuffles here.
8242   V1 = DAG.getBitcast(MVT::v2f64, V1);
8243   V2 = DAG.getBitcast(MVT::v2f64, V2);
8244   return DAG.getBitcast(MVT::v2i64,
8245                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8246 }
8247
8248 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8249 ///
8250 /// This is used to disable more specialized lowerings when the shufps lowering
8251 /// will happen to be efficient.
8252 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8253   // This routine only handles 128-bit shufps.
8254   assert(Mask.size() == 4 && "Unsupported mask size!");
8255
8256   // To lower with a single SHUFPS we need to have the low half and high half
8257   // each requiring a single input.
8258   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8259     return false;
8260   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8261     return false;
8262
8263   return true;
8264 }
8265
8266 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8267 ///
8268 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8269 /// It makes no assumptions about whether this is the *best* lowering, it simply
8270 /// uses it.
8271 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8272                                             ArrayRef<int> Mask, SDValue V1,
8273                                             SDValue V2, SelectionDAG &DAG) {
8274   SDValue LowV = V1, HighV = V2;
8275   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8276
8277   int NumV2Elements =
8278       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8279
8280   if (NumV2Elements == 1) {
8281     int V2Index =
8282         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8283         Mask.begin();
8284
8285     // Compute the index adjacent to V2Index and in the same half by toggling
8286     // the low bit.
8287     int V2AdjIndex = V2Index ^ 1;
8288
8289     if (Mask[V2AdjIndex] == -1) {
8290       // Handles all the cases where we have a single V2 element and an undef.
8291       // This will only ever happen in the high lanes because we commute the
8292       // vector otherwise.
8293       if (V2Index < 2)
8294         std::swap(LowV, HighV);
8295       NewMask[V2Index] -= 4;
8296     } else {
8297       // Handle the case where the V2 element ends up adjacent to a V1 element.
8298       // To make this work, blend them together as the first step.
8299       int V1Index = V2AdjIndex;
8300       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8301       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8302                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8303
8304       // Now proceed to reconstruct the final blend as we have the necessary
8305       // high or low half formed.
8306       if (V2Index < 2) {
8307         LowV = V2;
8308         HighV = V1;
8309       } else {
8310         HighV = V2;
8311       }
8312       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8313       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8314     }
8315   } else if (NumV2Elements == 2) {
8316     if (Mask[0] < 4 && Mask[1] < 4) {
8317       // Handle the easy case where we have V1 in the low lanes and V2 in the
8318       // high lanes.
8319       NewMask[2] -= 4;
8320       NewMask[3] -= 4;
8321     } else if (Mask[2] < 4 && Mask[3] < 4) {
8322       // We also handle the reversed case because this utility may get called
8323       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8324       // arrange things in the right direction.
8325       NewMask[0] -= 4;
8326       NewMask[1] -= 4;
8327       HighV = V1;
8328       LowV = V2;
8329     } else {
8330       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8331       // trying to place elements directly, just blend them and set up the final
8332       // shuffle to place them.
8333
8334       // The first two blend mask elements are for V1, the second two are for
8335       // V2.
8336       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8337                           Mask[2] < 4 ? Mask[2] : Mask[3],
8338                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8339                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8340       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8341                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8342
8343       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8344       // a blend.
8345       LowV = HighV = V1;
8346       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8347       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8348       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8349       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8350     }
8351   }
8352   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8353                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8354 }
8355
8356 /// \brief Lower 4-lane 32-bit floating point shuffles.
8357 ///
8358 /// Uses instructions exclusively from the floating point unit to minimize
8359 /// domain crossing penalties, as these are sufficient to implement all v4f32
8360 /// shuffles.
8361 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8362                                        const X86Subtarget *Subtarget,
8363                                        SelectionDAG &DAG) {
8364   SDLoc DL(Op);
8365   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8366   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8367   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8369   ArrayRef<int> Mask = SVOp->getMask();
8370   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8371
8372   int NumV2Elements =
8373       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8374
8375   if (NumV2Elements == 0) {
8376     // Check for being able to broadcast a single element.
8377     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8378                                                           Mask, Subtarget, DAG))
8379       return Broadcast;
8380
8381     // Use even/odd duplicate instructions for masks that match their pattern.
8382     if (Subtarget->hasSSE3()) {
8383       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8384         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8385       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8386         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8387     }
8388
8389     if (Subtarget->hasAVX()) {
8390       // If we have AVX, we can use VPERMILPS which will allow folding a load
8391       // into the shuffle.
8392       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8393                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8394     }
8395
8396     // Otherwise, use a straight shuffle of a single input vector. We pass the
8397     // input vector to both operands to simulate this with a SHUFPS.
8398     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8399                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8400   }
8401
8402   // There are special ways we can lower some single-element blends. However, we
8403   // have custom ways we can lower more complex single-element blends below that
8404   // we defer to if both this and BLENDPS fail to match, so restrict this to
8405   // when the V2 input is targeting element 0 of the mask -- that is the fast
8406   // case here.
8407   if (NumV2Elements == 1 && Mask[0] >= 4)
8408     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8409                                                          Mask, Subtarget, DAG))
8410       return V;
8411
8412   if (Subtarget->hasSSE41()) {
8413     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8414                                                   Subtarget, DAG))
8415       return Blend;
8416
8417     // Use INSERTPS if we can complete the shuffle efficiently.
8418     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8419       return V;
8420
8421     if (!isSingleSHUFPSMask(Mask))
8422       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8423               DL, MVT::v4f32, V1, V2, Mask, DAG))
8424         return BlendPerm;
8425   }
8426
8427   // Use dedicated unpack instructions for masks that match their pattern.
8428   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8429     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8430   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8431     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8432   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8433     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8434   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8435     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8436
8437   // Otherwise fall back to a SHUFPS lowering strategy.
8438   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8439 }
8440
8441 /// \brief Lower 4-lane i32 vector shuffles.
8442 ///
8443 /// We try to handle these with integer-domain shuffles where we can, but for
8444 /// blends we use the floating point domain blend instructions.
8445 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8446                                        const X86Subtarget *Subtarget,
8447                                        SelectionDAG &DAG) {
8448   SDLoc DL(Op);
8449   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8450   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8451   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8452   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8453   ArrayRef<int> Mask = SVOp->getMask();
8454   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8455
8456   // Whenever we can lower this as a zext, that instruction is strictly faster
8457   // than any alternative. It also allows us to fold memory operands into the
8458   // shuffle in many cases.
8459   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8460                                                          Mask, Subtarget, DAG))
8461     return ZExt;
8462
8463   int NumV2Elements =
8464       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8465
8466   if (NumV2Elements == 0) {
8467     // Check for being able to broadcast a single element.
8468     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8469                                                           Mask, Subtarget, DAG))
8470       return Broadcast;
8471
8472     // Straight shuffle of a single input vector. For everything from SSE2
8473     // onward this has a single fast instruction with no scary immediates.
8474     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8475     // but we aren't actually going to use the UNPCK instruction because doing
8476     // so prevents folding a load into this instruction or making a copy.
8477     const int UnpackLoMask[] = {0, 0, 1, 1};
8478     const int UnpackHiMask[] = {2, 2, 3, 3};
8479     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8480       Mask = UnpackLoMask;
8481     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8482       Mask = UnpackHiMask;
8483
8484     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8485                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8486   }
8487
8488   // Try to use shift instructions.
8489   if (SDValue Shift =
8490           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8491     return Shift;
8492
8493   // There are special ways we can lower some single-element blends.
8494   if (NumV2Elements == 1)
8495     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8496                                                          Mask, Subtarget, DAG))
8497       return V;
8498
8499   // We have different paths for blend lowering, but they all must use the
8500   // *exact* same predicate.
8501   bool IsBlendSupported = Subtarget->hasSSE41();
8502   if (IsBlendSupported)
8503     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8504                                                   Subtarget, DAG))
8505       return Blend;
8506
8507   if (SDValue Masked =
8508           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8509     return Masked;
8510
8511   // Use dedicated unpack instructions for masks that match their pattern.
8512   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8513     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8514   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8515     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8516   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8517     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8518   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8519     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8520
8521   // Try to use byte rotation instructions.
8522   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8523   if (Subtarget->hasSSSE3())
8524     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8525             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8526       return Rotate;
8527
8528   // If we have direct support for blends, we should lower by decomposing into
8529   // a permute. That will be faster than the domain cross.
8530   if (IsBlendSupported)
8531     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8532                                                       Mask, DAG);
8533
8534   // Try to lower by permuting the inputs into an unpack instruction.
8535   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8536                                                             V2, Mask, DAG))
8537     return Unpack;
8538
8539   // We implement this with SHUFPS because it can blend from two vectors.
8540   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8541   // up the inputs, bypassing domain shift penalties that we would encur if we
8542   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8543   // relevant.
8544   return DAG.getBitcast(
8545       MVT::v4i32,
8546       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8547                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8548 }
8549
8550 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8551 /// shuffle lowering, and the most complex part.
8552 ///
8553 /// The lowering strategy is to try to form pairs of input lanes which are
8554 /// targeted at the same half of the final vector, and then use a dword shuffle
8555 /// to place them onto the right half, and finally unpack the paired lanes into
8556 /// their final position.
8557 ///
8558 /// The exact breakdown of how to form these dword pairs and align them on the
8559 /// correct sides is really tricky. See the comments within the function for
8560 /// more of the details.
8561 ///
8562 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8563 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8564 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8565 /// vector, form the analogous 128-bit 8-element Mask.
8566 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8567     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8568     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8569   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8570   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8571
8572   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8573   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8574   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8575
8576   SmallVector<int, 4> LoInputs;
8577   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8578                [](int M) { return M >= 0; });
8579   std::sort(LoInputs.begin(), LoInputs.end());
8580   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8581   SmallVector<int, 4> HiInputs;
8582   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8583                [](int M) { return M >= 0; });
8584   std::sort(HiInputs.begin(), HiInputs.end());
8585   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8586   int NumLToL =
8587       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8588   int NumHToL = LoInputs.size() - NumLToL;
8589   int NumLToH =
8590       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8591   int NumHToH = HiInputs.size() - NumLToH;
8592   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8593   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8594   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8595   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8596
8597   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8598   // such inputs we can swap two of the dwords across the half mark and end up
8599   // with <=2 inputs to each half in each half. Once there, we can fall through
8600   // to the generic code below. For example:
8601   //
8602   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8603   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8604   //
8605   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8606   // and an existing 2-into-2 on the other half. In this case we may have to
8607   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8608   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8609   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8610   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8611   // half than the one we target for fixing) will be fixed when we re-enter this
8612   // path. We will also combine away any sequence of PSHUFD instructions that
8613   // result into a single instruction. Here is an example of the tricky case:
8614   //
8615   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8616   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8617   //
8618   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8619   //
8620   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8621   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8622   //
8623   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8624   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8625   //
8626   // The result is fine to be handled by the generic logic.
8627   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8628                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8629                           int AOffset, int BOffset) {
8630     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8631            "Must call this with A having 3 or 1 inputs from the A half.");
8632     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8633            "Must call this with B having 1 or 3 inputs from the B half.");
8634     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8635            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8636
8637     bool ThreeAInputs = AToAInputs.size() == 3;
8638
8639     // Compute the index of dword with only one word among the three inputs in
8640     // a half by taking the sum of the half with three inputs and subtracting
8641     // the sum of the actual three inputs. The difference is the remaining
8642     // slot.
8643     int ADWord, BDWord;
8644     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8645     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8646     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8647     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8648     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8649     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8650     int TripleNonInputIdx =
8651         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8652     TripleDWord = TripleNonInputIdx / 2;
8653
8654     // We use xor with one to compute the adjacent DWord to whichever one the
8655     // OneInput is in.
8656     OneInputDWord = (OneInput / 2) ^ 1;
8657
8658     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8659     // and BToA inputs. If there is also such a problem with the BToB and AToB
8660     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8661     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8662     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8663     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8664       // Compute how many inputs will be flipped by swapping these DWords. We
8665       // need
8666       // to balance this to ensure we don't form a 3-1 shuffle in the other
8667       // half.
8668       int NumFlippedAToBInputs =
8669           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8670           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8671       int NumFlippedBToBInputs =
8672           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8673           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8674       if ((NumFlippedAToBInputs == 1 &&
8675            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8676           (NumFlippedBToBInputs == 1 &&
8677            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8678         // We choose whether to fix the A half or B half based on whether that
8679         // half has zero flipped inputs. At zero, we may not be able to fix it
8680         // with that half. We also bias towards fixing the B half because that
8681         // will more commonly be the high half, and we have to bias one way.
8682         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8683                                                        ArrayRef<int> Inputs) {
8684           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8685           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8686                                          PinnedIdx ^ 1) != Inputs.end();
8687           // Determine whether the free index is in the flipped dword or the
8688           // unflipped dword based on where the pinned index is. We use this bit
8689           // in an xor to conditionally select the adjacent dword.
8690           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8691           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8692                                              FixFreeIdx) != Inputs.end();
8693           if (IsFixIdxInput == IsFixFreeIdxInput)
8694             FixFreeIdx += 1;
8695           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8696                                         FixFreeIdx) != Inputs.end();
8697           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8698                  "We need to be changing the number of flipped inputs!");
8699           int PSHUFHalfMask[] = {0, 1, 2, 3};
8700           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8701           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8702                           MVT::v8i16, V,
8703                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8704
8705           for (int &M : Mask)
8706             if (M != -1 && M == FixIdx)
8707               M = FixFreeIdx;
8708             else if (M != -1 && M == FixFreeIdx)
8709               M = FixIdx;
8710         };
8711         if (NumFlippedBToBInputs != 0) {
8712           int BPinnedIdx =
8713               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8714           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8715         } else {
8716           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8717           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8718           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8719         }
8720       }
8721     }
8722
8723     int PSHUFDMask[] = {0, 1, 2, 3};
8724     PSHUFDMask[ADWord] = BDWord;
8725     PSHUFDMask[BDWord] = ADWord;
8726     V = DAG.getBitcast(
8727         VT,
8728         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8729                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8730
8731     // Adjust the mask to match the new locations of A and B.
8732     for (int &M : Mask)
8733       if (M != -1 && M/2 == ADWord)
8734         M = 2 * BDWord + M % 2;
8735       else if (M != -1 && M/2 == BDWord)
8736         M = 2 * ADWord + M % 2;
8737
8738     // Recurse back into this routine to re-compute state now that this isn't
8739     // a 3 and 1 problem.
8740     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8741                                                      DAG);
8742   };
8743   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8744     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8745   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8746     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8747
8748   // At this point there are at most two inputs to the low and high halves from
8749   // each half. That means the inputs can always be grouped into dwords and
8750   // those dwords can then be moved to the correct half with a dword shuffle.
8751   // We use at most one low and one high word shuffle to collect these paired
8752   // inputs into dwords, and finally a dword shuffle to place them.
8753   int PSHUFLMask[4] = {-1, -1, -1, -1};
8754   int PSHUFHMask[4] = {-1, -1, -1, -1};
8755   int PSHUFDMask[4] = {-1, -1, -1, -1};
8756
8757   // First fix the masks for all the inputs that are staying in their
8758   // original halves. This will then dictate the targets of the cross-half
8759   // shuffles.
8760   auto fixInPlaceInputs =
8761       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8762                     MutableArrayRef<int> SourceHalfMask,
8763                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8764     if (InPlaceInputs.empty())
8765       return;
8766     if (InPlaceInputs.size() == 1) {
8767       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8768           InPlaceInputs[0] - HalfOffset;
8769       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8770       return;
8771     }
8772     if (IncomingInputs.empty()) {
8773       // Just fix all of the in place inputs.
8774       for (int Input : InPlaceInputs) {
8775         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8776         PSHUFDMask[Input / 2] = Input / 2;
8777       }
8778       return;
8779     }
8780
8781     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8782     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8783         InPlaceInputs[0] - HalfOffset;
8784     // Put the second input next to the first so that they are packed into
8785     // a dword. We find the adjacent index by toggling the low bit.
8786     int AdjIndex = InPlaceInputs[0] ^ 1;
8787     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8788     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8789     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8790   };
8791   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8792   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8793
8794   // Now gather the cross-half inputs and place them into a free dword of
8795   // their target half.
8796   // FIXME: This operation could almost certainly be simplified dramatically to
8797   // look more like the 3-1 fixing operation.
8798   auto moveInputsToRightHalf = [&PSHUFDMask](
8799       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8800       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8801       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8802       int DestOffset) {
8803     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8804       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8805     };
8806     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8807                                                int Word) {
8808       int LowWord = Word & ~1;
8809       int HighWord = Word | 1;
8810       return isWordClobbered(SourceHalfMask, LowWord) ||
8811              isWordClobbered(SourceHalfMask, HighWord);
8812     };
8813
8814     if (IncomingInputs.empty())
8815       return;
8816
8817     if (ExistingInputs.empty()) {
8818       // Map any dwords with inputs from them into the right half.
8819       for (int Input : IncomingInputs) {
8820         // If the source half mask maps over the inputs, turn those into
8821         // swaps and use the swapped lane.
8822         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8823           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8824             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8825                 Input - SourceOffset;
8826             // We have to swap the uses in our half mask in one sweep.
8827             for (int &M : HalfMask)
8828               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8829                 M = Input;
8830               else if (M == Input)
8831                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8832           } else {
8833             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8834                        Input - SourceOffset &&
8835                    "Previous placement doesn't match!");
8836           }
8837           // Note that this correctly re-maps both when we do a swap and when
8838           // we observe the other side of the swap above. We rely on that to
8839           // avoid swapping the members of the input list directly.
8840           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8841         }
8842
8843         // Map the input's dword into the correct half.
8844         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8845           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8846         else
8847           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8848                      Input / 2 &&
8849                  "Previous placement doesn't match!");
8850       }
8851
8852       // And just directly shift any other-half mask elements to be same-half
8853       // as we will have mirrored the dword containing the element into the
8854       // same position within that half.
8855       for (int &M : HalfMask)
8856         if (M >= SourceOffset && M < SourceOffset + 4) {
8857           M = M - SourceOffset + DestOffset;
8858           assert(M >= 0 && "This should never wrap below zero!");
8859         }
8860       return;
8861     }
8862
8863     // Ensure we have the input in a viable dword of its current half. This
8864     // is particularly tricky because the original position may be clobbered
8865     // by inputs being moved and *staying* in that half.
8866     if (IncomingInputs.size() == 1) {
8867       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8868         int InputFixed = std::find(std::begin(SourceHalfMask),
8869                                    std::end(SourceHalfMask), -1) -
8870                          std::begin(SourceHalfMask) + SourceOffset;
8871         SourceHalfMask[InputFixed - SourceOffset] =
8872             IncomingInputs[0] - SourceOffset;
8873         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8874                      InputFixed);
8875         IncomingInputs[0] = InputFixed;
8876       }
8877     } else if (IncomingInputs.size() == 2) {
8878       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8879           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8880         // We have two non-adjacent or clobbered inputs we need to extract from
8881         // the source half. To do this, we need to map them into some adjacent
8882         // dword slot in the source mask.
8883         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8884                               IncomingInputs[1] - SourceOffset};
8885
8886         // If there is a free slot in the source half mask adjacent to one of
8887         // the inputs, place the other input in it. We use (Index XOR 1) to
8888         // compute an adjacent index.
8889         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8890             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8891           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8892           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8893           InputsFixed[1] = InputsFixed[0] ^ 1;
8894         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8895                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8896           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8897           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8898           InputsFixed[0] = InputsFixed[1] ^ 1;
8899         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8900                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8901           // The two inputs are in the same DWord but it is clobbered and the
8902           // adjacent DWord isn't used at all. Move both inputs to the free
8903           // slot.
8904           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8905           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8906           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8907           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8908         } else {
8909           // The only way we hit this point is if there is no clobbering
8910           // (because there are no off-half inputs to this half) and there is no
8911           // free slot adjacent to one of the inputs. In this case, we have to
8912           // swap an input with a non-input.
8913           for (int i = 0; i < 4; ++i)
8914             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8915                    "We can't handle any clobbers here!");
8916           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8917                  "Cannot have adjacent inputs here!");
8918
8919           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8920           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8921
8922           // We also have to update the final source mask in this case because
8923           // it may need to undo the above swap.
8924           for (int &M : FinalSourceHalfMask)
8925             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8926               M = InputsFixed[1] + SourceOffset;
8927             else if (M == InputsFixed[1] + SourceOffset)
8928               M = (InputsFixed[0] ^ 1) + SourceOffset;
8929
8930           InputsFixed[1] = InputsFixed[0] ^ 1;
8931         }
8932
8933         // Point everything at the fixed inputs.
8934         for (int &M : HalfMask)
8935           if (M == IncomingInputs[0])
8936             M = InputsFixed[0] + SourceOffset;
8937           else if (M == IncomingInputs[1])
8938             M = InputsFixed[1] + SourceOffset;
8939
8940         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8941         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8942       }
8943     } else {
8944       llvm_unreachable("Unhandled input size!");
8945     }
8946
8947     // Now hoist the DWord down to the right half.
8948     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8949     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8950     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8951     for (int &M : HalfMask)
8952       for (int Input : IncomingInputs)
8953         if (M == Input)
8954           M = FreeDWord * 2 + Input % 2;
8955   };
8956   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8957                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8958   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8959                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8960
8961   // Now enact all the shuffles we've computed to move the inputs into their
8962   // target half.
8963   if (!isNoopShuffleMask(PSHUFLMask))
8964     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8965                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8966   if (!isNoopShuffleMask(PSHUFHMask))
8967     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8968                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8969   if (!isNoopShuffleMask(PSHUFDMask))
8970     V = DAG.getBitcast(
8971         VT,
8972         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8973                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8974
8975   // At this point, each half should contain all its inputs, and we can then
8976   // just shuffle them into their final position.
8977   assert(std::count_if(LoMask.begin(), LoMask.end(),
8978                        [](int M) { return M >= 4; }) == 0 &&
8979          "Failed to lift all the high half inputs to the low mask!");
8980   assert(std::count_if(HiMask.begin(), HiMask.end(),
8981                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8982          "Failed to lift all the low half inputs to the high mask!");
8983
8984   // Do a half shuffle for the low mask.
8985   if (!isNoopShuffleMask(LoMask))
8986     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8987                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8988
8989   // Do a half shuffle with the high mask after shifting its values down.
8990   for (int &M : HiMask)
8991     if (M >= 0)
8992       M -= 4;
8993   if (!isNoopShuffleMask(HiMask))
8994     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8995                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8996
8997   return V;
8998 }
8999
9000 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9001 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9002                                           SDValue V2, ArrayRef<int> Mask,
9003                                           SelectionDAG &DAG, bool &V1InUse,
9004                                           bool &V2InUse) {
9005   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9006   SDValue V1Mask[16];
9007   SDValue V2Mask[16];
9008   V1InUse = false;
9009   V2InUse = false;
9010
9011   int Size = Mask.size();
9012   int Scale = 16 / Size;
9013   for (int i = 0; i < 16; ++i) {
9014     if (Mask[i / Scale] == -1) {
9015       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9016     } else {
9017       const int ZeroMask = 0x80;
9018       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9019                                           : ZeroMask;
9020       int V2Idx = Mask[i / Scale] < Size
9021                       ? ZeroMask
9022                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9023       if (Zeroable[i / Scale])
9024         V1Idx = V2Idx = ZeroMask;
9025       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9026       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9027       V1InUse |= (ZeroMask != V1Idx);
9028       V2InUse |= (ZeroMask != V2Idx);
9029     }
9030   }
9031
9032   if (V1InUse)
9033     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9034                      DAG.getBitcast(MVT::v16i8, V1),
9035                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9036   if (V2InUse)
9037     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9038                      DAG.getBitcast(MVT::v16i8, V2),
9039                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9040
9041   // If we need shuffled inputs from both, blend the two.
9042   SDValue V;
9043   if (V1InUse && V2InUse)
9044     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9045   else
9046     V = V1InUse ? V1 : V2;
9047
9048   // Cast the result back to the correct type.
9049   return DAG.getBitcast(VT, V);
9050 }
9051
9052 /// \brief Generic lowering of 8-lane i16 shuffles.
9053 ///
9054 /// This handles both single-input shuffles and combined shuffle/blends with
9055 /// two inputs. The single input shuffles are immediately delegated to
9056 /// a dedicated lowering routine.
9057 ///
9058 /// The blends are lowered in one of three fundamental ways. If there are few
9059 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9060 /// of the input is significantly cheaper when lowered as an interleaving of
9061 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9062 /// halves of the inputs separately (making them have relatively few inputs)
9063 /// and then concatenate them.
9064 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9065                                        const X86Subtarget *Subtarget,
9066                                        SelectionDAG &DAG) {
9067   SDLoc DL(Op);
9068   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9069   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9070   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9071   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9072   ArrayRef<int> OrigMask = SVOp->getMask();
9073   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9074                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9075   MutableArrayRef<int> Mask(MaskStorage);
9076
9077   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9078
9079   // Whenever we can lower this as a zext, that instruction is strictly faster
9080   // than any alternative.
9081   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9082           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9083     return ZExt;
9084
9085   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9086   (void)isV1;
9087   auto isV2 = [](int M) { return M >= 8; };
9088
9089   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9090
9091   if (NumV2Inputs == 0) {
9092     // Check for being able to broadcast a single element.
9093     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9094                                                           Mask, Subtarget, DAG))
9095       return Broadcast;
9096
9097     // Try to use shift instructions.
9098     if (SDValue Shift =
9099             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9100       return Shift;
9101
9102     // Use dedicated unpack instructions for masks that match their pattern.
9103     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9104       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9105     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9106       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9107
9108     // Try to use byte rotation instructions.
9109     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9110                                                         Mask, Subtarget, DAG))
9111       return Rotate;
9112
9113     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9114                                                      Subtarget, DAG);
9115   }
9116
9117   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9118          "All single-input shuffles should be canonicalized to be V1-input "
9119          "shuffles.");
9120
9121   // Try to use shift instructions.
9122   if (SDValue Shift =
9123           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9124     return Shift;
9125
9126   // See if we can use SSE4A Extraction / Insertion.
9127   if (Subtarget->hasSSE4A())
9128     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9129       return V;
9130
9131   // There are special ways we can lower some single-element blends.
9132   if (NumV2Inputs == 1)
9133     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9134                                                          Mask, Subtarget, DAG))
9135       return V;
9136
9137   // We have different paths for blend lowering, but they all must use the
9138   // *exact* same predicate.
9139   bool IsBlendSupported = Subtarget->hasSSE41();
9140   if (IsBlendSupported)
9141     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9142                                                   Subtarget, DAG))
9143       return Blend;
9144
9145   if (SDValue Masked =
9146           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9147     return Masked;
9148
9149   // Use dedicated unpack instructions for masks that match their pattern.
9150   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9151     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9152   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9153     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9154
9155   // Try to use byte rotation instructions.
9156   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9157           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9158     return Rotate;
9159
9160   if (SDValue BitBlend =
9161           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9162     return BitBlend;
9163
9164   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9165                                                             V2, Mask, DAG))
9166     return Unpack;
9167
9168   // If we can't directly blend but can use PSHUFB, that will be better as it
9169   // can both shuffle and set up the inefficient blend.
9170   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9171     bool V1InUse, V2InUse;
9172     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9173                                       V1InUse, V2InUse);
9174   }
9175
9176   // We can always bit-blend if we have to so the fallback strategy is to
9177   // decompose into single-input permutes and blends.
9178   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9179                                                       Mask, DAG);
9180 }
9181
9182 /// \brief Check whether a compaction lowering can be done by dropping even
9183 /// elements and compute how many times even elements must be dropped.
9184 ///
9185 /// This handles shuffles which take every Nth element where N is a power of
9186 /// two. Example shuffle masks:
9187 ///
9188 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9189 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9190 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9191 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9192 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9193 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9194 ///
9195 /// Any of these lanes can of course be undef.
9196 ///
9197 /// This routine only supports N <= 3.
9198 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9199 /// for larger N.
9200 ///
9201 /// \returns N above, or the number of times even elements must be dropped if
9202 /// there is such a number. Otherwise returns zero.
9203 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9204   // Figure out whether we're looping over two inputs or just one.
9205   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9206
9207   // The modulus for the shuffle vector entries is based on whether this is
9208   // a single input or not.
9209   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9210   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9211          "We should only be called with masks with a power-of-2 size!");
9212
9213   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9214
9215   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9216   // and 2^3 simultaneously. This is because we may have ambiguity with
9217   // partially undef inputs.
9218   bool ViableForN[3] = {true, true, true};
9219
9220   for (int i = 0, e = Mask.size(); i < e; ++i) {
9221     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9222     // want.
9223     if (Mask[i] == -1)
9224       continue;
9225
9226     bool IsAnyViable = false;
9227     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9228       if (ViableForN[j]) {
9229         uint64_t N = j + 1;
9230
9231         // The shuffle mask must be equal to (i * 2^N) % M.
9232         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9233           IsAnyViable = true;
9234         else
9235           ViableForN[j] = false;
9236       }
9237     // Early exit if we exhaust the possible powers of two.
9238     if (!IsAnyViable)
9239       break;
9240   }
9241
9242   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9243     if (ViableForN[j])
9244       return j + 1;
9245
9246   // Return 0 as there is no viable power of two.
9247   return 0;
9248 }
9249
9250 /// \brief Generic lowering of v16i8 shuffles.
9251 ///
9252 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9253 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9254 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9255 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9256 /// back together.
9257 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9258                                        const X86Subtarget *Subtarget,
9259                                        SelectionDAG &DAG) {
9260   SDLoc DL(Op);
9261   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9262   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9263   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9264   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9265   ArrayRef<int> Mask = SVOp->getMask();
9266   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9267
9268   // Try to use shift instructions.
9269   if (SDValue Shift =
9270           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9271     return Shift;
9272
9273   // Try to use byte rotation instructions.
9274   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9275           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9276     return Rotate;
9277
9278   // Try to use a zext lowering.
9279   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9280           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9281     return ZExt;
9282
9283   // See if we can use SSE4A Extraction / Insertion.
9284   if (Subtarget->hasSSE4A())
9285     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9286       return V;
9287
9288   int NumV2Elements =
9289       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9290
9291   // For single-input shuffles, there are some nicer lowering tricks we can use.
9292   if (NumV2Elements == 0) {
9293     // Check for being able to broadcast a single element.
9294     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9295                                                           Mask, Subtarget, DAG))
9296       return Broadcast;
9297
9298     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9299     // Notably, this handles splat and partial-splat shuffles more efficiently.
9300     // However, it only makes sense if the pre-duplication shuffle simplifies
9301     // things significantly. Currently, this means we need to be able to
9302     // express the pre-duplication shuffle as an i16 shuffle.
9303     //
9304     // FIXME: We should check for other patterns which can be widened into an
9305     // i16 shuffle as well.
9306     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9307       for (int i = 0; i < 16; i += 2)
9308         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9309           return false;
9310
9311       return true;
9312     };
9313     auto tryToWidenViaDuplication = [&]() -> SDValue {
9314       if (!canWidenViaDuplication(Mask))
9315         return SDValue();
9316       SmallVector<int, 4> LoInputs;
9317       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9318                    [](int M) { return M >= 0 && M < 8; });
9319       std::sort(LoInputs.begin(), LoInputs.end());
9320       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9321                      LoInputs.end());
9322       SmallVector<int, 4> HiInputs;
9323       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9324                    [](int M) { return M >= 8; });
9325       std::sort(HiInputs.begin(), HiInputs.end());
9326       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9327                      HiInputs.end());
9328
9329       bool TargetLo = LoInputs.size() >= HiInputs.size();
9330       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9331       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9332
9333       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9334       SmallDenseMap<int, int, 8> LaneMap;
9335       for (int I : InPlaceInputs) {
9336         PreDupI16Shuffle[I/2] = I/2;
9337         LaneMap[I] = I;
9338       }
9339       int j = TargetLo ? 0 : 4, je = j + 4;
9340       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9341         // Check if j is already a shuffle of this input. This happens when
9342         // there are two adjacent bytes after we move the low one.
9343         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9344           // If we haven't yet mapped the input, search for a slot into which
9345           // we can map it.
9346           while (j < je && PreDupI16Shuffle[j] != -1)
9347             ++j;
9348
9349           if (j == je)
9350             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9351             return SDValue();
9352
9353           // Map this input with the i16 shuffle.
9354           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9355         }
9356
9357         // Update the lane map based on the mapping we ended up with.
9358         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9359       }
9360       V1 = DAG.getBitcast(
9361           MVT::v16i8,
9362           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9363                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9364
9365       // Unpack the bytes to form the i16s that will be shuffled into place.
9366       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9367                        MVT::v16i8, V1, V1);
9368
9369       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9370       for (int i = 0; i < 16; ++i)
9371         if (Mask[i] != -1) {
9372           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9373           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9374           if (PostDupI16Shuffle[i / 2] == -1)
9375             PostDupI16Shuffle[i / 2] = MappedMask;
9376           else
9377             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9378                    "Conflicting entrties in the original shuffle!");
9379         }
9380       return DAG.getBitcast(
9381           MVT::v16i8,
9382           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9383                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9384     };
9385     if (SDValue V = tryToWidenViaDuplication())
9386       return V;
9387   }
9388
9389   if (SDValue Masked =
9390           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9391     return Masked;
9392
9393   // Use dedicated unpack instructions for masks that match their pattern.
9394   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9395                                          0, 16, 1, 17, 2, 18, 3, 19,
9396                                          // High half.
9397                                          4, 20, 5, 21, 6, 22, 7, 23}))
9398     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9399   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9400                                          8, 24, 9, 25, 10, 26, 11, 27,
9401                                          // High half.
9402                                          12, 28, 13, 29, 14, 30, 15, 31}))
9403     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9404
9405   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9406   // with PSHUFB. It is important to do this before we attempt to generate any
9407   // blends but after all of the single-input lowerings. If the single input
9408   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9409   // want to preserve that and we can DAG combine any longer sequences into
9410   // a PSHUFB in the end. But once we start blending from multiple inputs,
9411   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9412   // and there are *very* few patterns that would actually be faster than the
9413   // PSHUFB approach because of its ability to zero lanes.
9414   //
9415   // FIXME: The only exceptions to the above are blends which are exact
9416   // interleavings with direct instructions supporting them. We currently don't
9417   // handle those well here.
9418   if (Subtarget->hasSSSE3()) {
9419     bool V1InUse = false;
9420     bool V2InUse = false;
9421
9422     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9423                                                 DAG, V1InUse, V2InUse);
9424
9425     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9426     // do so. This avoids using them to handle blends-with-zero which is
9427     // important as a single pshufb is significantly faster for that.
9428     if (V1InUse && V2InUse) {
9429       if (Subtarget->hasSSE41())
9430         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9431                                                       Mask, Subtarget, DAG))
9432           return Blend;
9433
9434       // We can use an unpack to do the blending rather than an or in some
9435       // cases. Even though the or may be (very minorly) more efficient, we
9436       // preference this lowering because there are common cases where part of
9437       // the complexity of the shuffles goes away when we do the final blend as
9438       // an unpack.
9439       // FIXME: It might be worth trying to detect if the unpack-feeding
9440       // shuffles will both be pshufb, in which case we shouldn't bother with
9441       // this.
9442       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9443               DL, MVT::v16i8, V1, V2, Mask, DAG))
9444         return Unpack;
9445     }
9446
9447     return PSHUFB;
9448   }
9449
9450   // There are special ways we can lower some single-element blends.
9451   if (NumV2Elements == 1)
9452     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9453                                                          Mask, Subtarget, DAG))
9454       return V;
9455
9456   if (SDValue BitBlend =
9457           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9458     return BitBlend;
9459
9460   // Check whether a compaction lowering can be done. This handles shuffles
9461   // which take every Nth element for some even N. See the helper function for
9462   // details.
9463   //
9464   // We special case these as they can be particularly efficiently handled with
9465   // the PACKUSB instruction on x86 and they show up in common patterns of
9466   // rearranging bytes to truncate wide elements.
9467   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9468     // NumEvenDrops is the power of two stride of the elements. Another way of
9469     // thinking about it is that we need to drop the even elements this many
9470     // times to get the original input.
9471     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9472
9473     // First we need to zero all the dropped bytes.
9474     assert(NumEvenDrops <= 3 &&
9475            "No support for dropping even elements more than 3 times.");
9476     // We use the mask type to pick which bytes are preserved based on how many
9477     // elements are dropped.
9478     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9479     SDValue ByteClearMask = DAG.getBitcast(
9480         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9481     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9482     if (!IsSingleInput)
9483       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9484
9485     // Now pack things back together.
9486     V1 = DAG.getBitcast(MVT::v8i16, V1);
9487     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9488     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9489     for (int i = 1; i < NumEvenDrops; ++i) {
9490       Result = DAG.getBitcast(MVT::v8i16, Result);
9491       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9492     }
9493
9494     return Result;
9495   }
9496
9497   // Handle multi-input cases by blending single-input shuffles.
9498   if (NumV2Elements > 0)
9499     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9500                                                       Mask, DAG);
9501
9502   // The fallback path for single-input shuffles widens this into two v8i16
9503   // vectors with unpacks, shuffles those, and then pulls them back together
9504   // with a pack.
9505   SDValue V = V1;
9506
9507   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9508   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9509   for (int i = 0; i < 16; ++i)
9510     if (Mask[i] >= 0)
9511       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9512
9513   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9514
9515   SDValue VLoHalf, VHiHalf;
9516   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9517   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9518   // i16s.
9519   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9520                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9521       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9522                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9523     // Use a mask to drop the high bytes.
9524     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9525     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9526                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9527
9528     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9529     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9530
9531     // Squash the masks to point directly into VLoHalf.
9532     for (int &M : LoBlendMask)
9533       if (M >= 0)
9534         M /= 2;
9535     for (int &M : HiBlendMask)
9536       if (M >= 0)
9537         M /= 2;
9538   } else {
9539     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9540     // VHiHalf so that we can blend them as i16s.
9541     VLoHalf = DAG.getBitcast(
9542         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9543     VHiHalf = DAG.getBitcast(
9544         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9545   }
9546
9547   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9548   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9549
9550   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9551 }
9552
9553 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9554 ///
9555 /// This routine breaks down the specific type of 128-bit shuffle and
9556 /// dispatches to the lowering routines accordingly.
9557 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9558                                         MVT VT, const X86Subtarget *Subtarget,
9559                                         SelectionDAG &DAG) {
9560   switch (VT.SimpleTy) {
9561   case MVT::v2i64:
9562     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9563   case MVT::v2f64:
9564     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9565   case MVT::v4i32:
9566     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9567   case MVT::v4f32:
9568     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9569   case MVT::v8i16:
9570     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9571   case MVT::v16i8:
9572     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9573
9574   default:
9575     llvm_unreachable("Unimplemented!");
9576   }
9577 }
9578
9579 /// \brief Helper function to test whether a shuffle mask could be
9580 /// simplified by widening the elements being shuffled.
9581 ///
9582 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9583 /// leaves it in an unspecified state.
9584 ///
9585 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9586 /// shuffle masks. The latter have the special property of a '-2' representing
9587 /// a zero-ed lane of a vector.
9588 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9589                                     SmallVectorImpl<int> &WidenedMask) {
9590   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9591     // If both elements are undef, its trivial.
9592     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9593       WidenedMask.push_back(SM_SentinelUndef);
9594       continue;
9595     }
9596
9597     // Check for an undef mask and a mask value properly aligned to fit with
9598     // a pair of values. If we find such a case, use the non-undef mask's value.
9599     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9600       WidenedMask.push_back(Mask[i + 1] / 2);
9601       continue;
9602     }
9603     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9604       WidenedMask.push_back(Mask[i] / 2);
9605       continue;
9606     }
9607
9608     // When zeroing, we need to spread the zeroing across both lanes to widen.
9609     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9610       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9611           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9612         WidenedMask.push_back(SM_SentinelZero);
9613         continue;
9614       }
9615       return false;
9616     }
9617
9618     // Finally check if the two mask values are adjacent and aligned with
9619     // a pair.
9620     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9621       WidenedMask.push_back(Mask[i] / 2);
9622       continue;
9623     }
9624
9625     // Otherwise we can't safely widen the elements used in this shuffle.
9626     return false;
9627   }
9628   assert(WidenedMask.size() == Mask.size() / 2 &&
9629          "Incorrect size of mask after widening the elements!");
9630
9631   return true;
9632 }
9633
9634 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9635 ///
9636 /// This routine just extracts two subvectors, shuffles them independently, and
9637 /// then concatenates them back together. This should work effectively with all
9638 /// AVX vector shuffle types.
9639 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9640                                           SDValue V2, ArrayRef<int> Mask,
9641                                           SelectionDAG &DAG) {
9642   assert(VT.getSizeInBits() >= 256 &&
9643          "Only for 256-bit or wider vector shuffles!");
9644   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9645   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9646
9647   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9648   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9649
9650   int NumElements = VT.getVectorNumElements();
9651   int SplitNumElements = NumElements / 2;
9652   MVT ScalarVT = VT.getScalarType();
9653   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9654
9655   // Rather than splitting build-vectors, just build two narrower build
9656   // vectors. This helps shuffling with splats and zeros.
9657   auto SplitVector = [&](SDValue V) {
9658     while (V.getOpcode() == ISD::BITCAST)
9659       V = V->getOperand(0);
9660
9661     MVT OrigVT = V.getSimpleValueType();
9662     int OrigNumElements = OrigVT.getVectorNumElements();
9663     int OrigSplitNumElements = OrigNumElements / 2;
9664     MVT OrigScalarVT = OrigVT.getScalarType();
9665     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9666
9667     SDValue LoV, HiV;
9668
9669     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9670     if (!BV) {
9671       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9672                         DAG.getIntPtrConstant(0, DL));
9673       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9674                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9675     } else {
9676
9677       SmallVector<SDValue, 16> LoOps, HiOps;
9678       for (int i = 0; i < OrigSplitNumElements; ++i) {
9679         LoOps.push_back(BV->getOperand(i));
9680         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9681       }
9682       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9683       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9684     }
9685     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9686                           DAG.getBitcast(SplitVT, HiV));
9687   };
9688
9689   SDValue LoV1, HiV1, LoV2, HiV2;
9690   std::tie(LoV1, HiV1) = SplitVector(V1);
9691   std::tie(LoV2, HiV2) = SplitVector(V2);
9692
9693   // Now create two 4-way blends of these half-width vectors.
9694   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9695     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9696     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9697     for (int i = 0; i < SplitNumElements; ++i) {
9698       int M = HalfMask[i];
9699       if (M >= NumElements) {
9700         if (M >= NumElements + SplitNumElements)
9701           UseHiV2 = true;
9702         else
9703           UseLoV2 = true;
9704         V2BlendMask.push_back(M - NumElements);
9705         V1BlendMask.push_back(-1);
9706         BlendMask.push_back(SplitNumElements + i);
9707       } else if (M >= 0) {
9708         if (M >= SplitNumElements)
9709           UseHiV1 = true;
9710         else
9711           UseLoV1 = true;
9712         V2BlendMask.push_back(-1);
9713         V1BlendMask.push_back(M);
9714         BlendMask.push_back(i);
9715       } else {
9716         V2BlendMask.push_back(-1);
9717         V1BlendMask.push_back(-1);
9718         BlendMask.push_back(-1);
9719       }
9720     }
9721
9722     // Because the lowering happens after all combining takes place, we need to
9723     // manually combine these blend masks as much as possible so that we create
9724     // a minimal number of high-level vector shuffle nodes.
9725
9726     // First try just blending the halves of V1 or V2.
9727     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9728       return DAG.getUNDEF(SplitVT);
9729     if (!UseLoV2 && !UseHiV2)
9730       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9731     if (!UseLoV1 && !UseHiV1)
9732       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9733
9734     SDValue V1Blend, V2Blend;
9735     if (UseLoV1 && UseHiV1) {
9736       V1Blend =
9737         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9738     } else {
9739       // We only use half of V1 so map the usage down into the final blend mask.
9740       V1Blend = UseLoV1 ? LoV1 : HiV1;
9741       for (int i = 0; i < SplitNumElements; ++i)
9742         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9743           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9744     }
9745     if (UseLoV2 && UseHiV2) {
9746       V2Blend =
9747         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9748     } else {
9749       // We only use half of V2 so map the usage down into the final blend mask.
9750       V2Blend = UseLoV2 ? LoV2 : HiV2;
9751       for (int i = 0; i < SplitNumElements; ++i)
9752         if (BlendMask[i] >= SplitNumElements)
9753           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9754     }
9755     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9756   };
9757   SDValue Lo = HalfBlend(LoMask);
9758   SDValue Hi = HalfBlend(HiMask);
9759   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9760 }
9761
9762 /// \brief Either split a vector in halves or decompose the shuffles and the
9763 /// blend.
9764 ///
9765 /// This is provided as a good fallback for many lowerings of non-single-input
9766 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9767 /// between splitting the shuffle into 128-bit components and stitching those
9768 /// back together vs. extracting the single-input shuffles and blending those
9769 /// results.
9770 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9771                                                 SDValue V2, ArrayRef<int> Mask,
9772                                                 SelectionDAG &DAG) {
9773   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9774                                             "lower single-input shuffles as it "
9775                                             "could then recurse on itself.");
9776   int Size = Mask.size();
9777
9778   // If this can be modeled as a broadcast of two elements followed by a blend,
9779   // prefer that lowering. This is especially important because broadcasts can
9780   // often fold with memory operands.
9781   auto DoBothBroadcast = [&] {
9782     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9783     for (int M : Mask)
9784       if (M >= Size) {
9785         if (V2BroadcastIdx == -1)
9786           V2BroadcastIdx = M - Size;
9787         else if (M - Size != V2BroadcastIdx)
9788           return false;
9789       } else if (M >= 0) {
9790         if (V1BroadcastIdx == -1)
9791           V1BroadcastIdx = M;
9792         else if (M != V1BroadcastIdx)
9793           return false;
9794       }
9795     return true;
9796   };
9797   if (DoBothBroadcast())
9798     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9799                                                       DAG);
9800
9801   // If the inputs all stem from a single 128-bit lane of each input, then we
9802   // split them rather than blending because the split will decompose to
9803   // unusually few instructions.
9804   int LaneCount = VT.getSizeInBits() / 128;
9805   int LaneSize = Size / LaneCount;
9806   SmallBitVector LaneInputs[2];
9807   LaneInputs[0].resize(LaneCount, false);
9808   LaneInputs[1].resize(LaneCount, false);
9809   for (int i = 0; i < Size; ++i)
9810     if (Mask[i] >= 0)
9811       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9812   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9813     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9814
9815   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9816   // that the decomposed single-input shuffles don't end up here.
9817   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9818 }
9819
9820 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9821 /// a permutation and blend of those lanes.
9822 ///
9823 /// This essentially blends the out-of-lane inputs to each lane into the lane
9824 /// from a permuted copy of the vector. This lowering strategy results in four
9825 /// instructions in the worst case for a single-input cross lane shuffle which
9826 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9827 /// of. Special cases for each particular shuffle pattern should be handled
9828 /// prior to trying this lowering.
9829 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9830                                                        SDValue V1, SDValue V2,
9831                                                        ArrayRef<int> Mask,
9832                                                        SelectionDAG &DAG) {
9833   // FIXME: This should probably be generalized for 512-bit vectors as well.
9834   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9835   int LaneSize = Mask.size() / 2;
9836
9837   // If there are only inputs from one 128-bit lane, splitting will in fact be
9838   // less expensive. The flags track whether the given lane contains an element
9839   // that crosses to another lane.
9840   bool LaneCrossing[2] = {false, false};
9841   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9842     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9843       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9844   if (!LaneCrossing[0] || !LaneCrossing[1])
9845     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9846
9847   if (isSingleInputShuffleMask(Mask)) {
9848     SmallVector<int, 32> FlippedBlendMask;
9849     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9850       FlippedBlendMask.push_back(
9851           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9852                                   ? Mask[i]
9853                                   : Mask[i] % LaneSize +
9854                                         (i / LaneSize) * LaneSize + Size));
9855
9856     // Flip the vector, and blend the results which should now be in-lane. The
9857     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9858     // 5 for the high source. The value 3 selects the high half of source 2 and
9859     // the value 2 selects the low half of source 2. We only use source 2 to
9860     // allow folding it into a memory operand.
9861     unsigned PERMMask = 3 | 2 << 4;
9862     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9863                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9864     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9865   }
9866
9867   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9868   // will be handled by the above logic and a blend of the results, much like
9869   // other patterns in AVX.
9870   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9871 }
9872
9873 /// \brief Handle lowering 2-lane 128-bit shuffles.
9874 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9875                                         SDValue V2, ArrayRef<int> Mask,
9876                                         const X86Subtarget *Subtarget,
9877                                         SelectionDAG &DAG) {
9878   // TODO: If minimizing size and one of the inputs is a zero vector and the
9879   // the zero vector has only one use, we could use a VPERM2X128 to save the
9880   // instruction bytes needed to explicitly generate the zero vector.
9881
9882   // Blends are faster and handle all the non-lane-crossing cases.
9883   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9884                                                 Subtarget, DAG))
9885     return Blend;
9886
9887   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9888   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9889
9890   // If either input operand is a zero vector, use VPERM2X128 because its mask
9891   // allows us to replace the zero input with an implicit zero.
9892   if (!IsV1Zero && !IsV2Zero) {
9893     // Check for patterns which can be matched with a single insert of a 128-bit
9894     // subvector.
9895     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9896     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9897       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9898                                    VT.getVectorNumElements() / 2);
9899       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9900                                 DAG.getIntPtrConstant(0, DL));
9901       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9902                                 OnlyUsesV1 ? V1 : V2,
9903                                 DAG.getIntPtrConstant(0, DL));
9904       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9905     }
9906   }
9907
9908   // Otherwise form a 128-bit permutation. After accounting for undefs,
9909   // convert the 64-bit shuffle mask selection values into 128-bit
9910   // selection bits by dividing the indexes by 2 and shifting into positions
9911   // defined by a vperm2*128 instruction's immediate control byte.
9912
9913   // The immediate permute control byte looks like this:
9914   //    [1:0] - select 128 bits from sources for low half of destination
9915   //    [2]   - ignore
9916   //    [3]   - zero low half of destination
9917   //    [5:4] - select 128 bits from sources for high half of destination
9918   //    [6]   - ignore
9919   //    [7]   - zero high half of destination
9920
9921   int MaskLO = Mask[0];
9922   if (MaskLO == SM_SentinelUndef)
9923     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9924
9925   int MaskHI = Mask[2];
9926   if (MaskHI == SM_SentinelUndef)
9927     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9928
9929   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9930
9931   // If either input is a zero vector, replace it with an undef input.
9932   // Shuffle mask values <  4 are selecting elements of V1.
9933   // Shuffle mask values >= 4 are selecting elements of V2.
9934   // Adjust each half of the permute mask by clearing the half that was
9935   // selecting the zero vector and setting the zero mask bit.
9936   if (IsV1Zero) {
9937     V1 = DAG.getUNDEF(VT);
9938     if (MaskLO < 4)
9939       PermMask = (PermMask & 0xf0) | 0x08;
9940     if (MaskHI < 4)
9941       PermMask = (PermMask & 0x0f) | 0x80;
9942   }
9943   if (IsV2Zero) {
9944     V2 = DAG.getUNDEF(VT);
9945     if (MaskLO >= 4)
9946       PermMask = (PermMask & 0xf0) | 0x08;
9947     if (MaskHI >= 4)
9948       PermMask = (PermMask & 0x0f) | 0x80;
9949   }
9950
9951   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9952                      DAG.getConstant(PermMask, DL, MVT::i8));
9953 }
9954
9955 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9956 /// shuffling each lane.
9957 ///
9958 /// This will only succeed when the result of fixing the 128-bit lanes results
9959 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9960 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9961 /// the lane crosses early and then use simpler shuffles within each lane.
9962 ///
9963 /// FIXME: It might be worthwhile at some point to support this without
9964 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9965 /// in x86 only floating point has interesting non-repeating shuffles, and even
9966 /// those are still *marginally* more expensive.
9967 static SDValue lowerVectorShuffleByMerging128BitLanes(
9968     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9969     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9970   assert(!isSingleInputShuffleMask(Mask) &&
9971          "This is only useful with multiple inputs.");
9972
9973   int Size = Mask.size();
9974   int LaneSize = 128 / VT.getScalarSizeInBits();
9975   int NumLanes = Size / LaneSize;
9976   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9977
9978   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9979   // check whether the in-128-bit lane shuffles share a repeating pattern.
9980   SmallVector<int, 4> Lanes;
9981   Lanes.resize(NumLanes, -1);
9982   SmallVector<int, 4> InLaneMask;
9983   InLaneMask.resize(LaneSize, -1);
9984   for (int i = 0; i < Size; ++i) {
9985     if (Mask[i] < 0)
9986       continue;
9987
9988     int j = i / LaneSize;
9989
9990     if (Lanes[j] < 0) {
9991       // First entry we've seen for this lane.
9992       Lanes[j] = Mask[i] / LaneSize;
9993     } else if (Lanes[j] != Mask[i] / LaneSize) {
9994       // This doesn't match the lane selected previously!
9995       return SDValue();
9996     }
9997
9998     // Check that within each lane we have a consistent shuffle mask.
9999     int k = i % LaneSize;
10000     if (InLaneMask[k] < 0) {
10001       InLaneMask[k] = Mask[i] % LaneSize;
10002     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10003       // This doesn't fit a repeating in-lane mask.
10004       return SDValue();
10005     }
10006   }
10007
10008   // First shuffle the lanes into place.
10009   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10010                                 VT.getSizeInBits() / 64);
10011   SmallVector<int, 8> LaneMask;
10012   LaneMask.resize(NumLanes * 2, -1);
10013   for (int i = 0; i < NumLanes; ++i)
10014     if (Lanes[i] >= 0) {
10015       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10016       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10017     }
10018
10019   V1 = DAG.getBitcast(LaneVT, V1);
10020   V2 = DAG.getBitcast(LaneVT, V2);
10021   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10022
10023   // Cast it back to the type we actually want.
10024   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10025
10026   // Now do a simple shuffle that isn't lane crossing.
10027   SmallVector<int, 8> NewMask;
10028   NewMask.resize(Size, -1);
10029   for (int i = 0; i < Size; ++i)
10030     if (Mask[i] >= 0)
10031       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10032   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10033          "Must not introduce lane crosses at this point!");
10034
10035   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10036 }
10037
10038 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10039 /// given mask.
10040 ///
10041 /// This returns true if the elements from a particular input are already in the
10042 /// slot required by the given mask and require no permutation.
10043 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10044   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10045   int Size = Mask.size();
10046   for (int i = 0; i < Size; ++i)
10047     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10048       return false;
10049
10050   return true;
10051 }
10052
10053 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10054                                             ArrayRef<int> Mask, SDValue V1,
10055                                             SDValue V2, SelectionDAG &DAG) {
10056
10057   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10058   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10059   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10060   int NumElts = VT.getVectorNumElements();
10061   bool ShufpdMask = true;
10062   bool CommutableMask = true;
10063   unsigned Immediate = 0;
10064   for (int i = 0; i < NumElts; ++i) {
10065     if (Mask[i] < 0)
10066       continue;
10067     int Val = (i & 6) + NumElts * (i & 1);
10068     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10069     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10070       ShufpdMask = false;
10071     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10072       CommutableMask = false;
10073     Immediate |= (Mask[i] % 2) << i;
10074   }
10075   if (ShufpdMask)
10076     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10077                        DAG.getConstant(Immediate, DL, MVT::i8));
10078   if (CommutableMask)
10079     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10080                        DAG.getConstant(Immediate, DL, MVT::i8));
10081   return SDValue();
10082 }
10083
10084 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10085 ///
10086 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10087 /// isn't available.
10088 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10089                                        const X86Subtarget *Subtarget,
10090                                        SelectionDAG &DAG) {
10091   SDLoc DL(Op);
10092   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10093   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10094   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10095   ArrayRef<int> Mask = SVOp->getMask();
10096   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10097
10098   SmallVector<int, 4> WidenedMask;
10099   if (canWidenShuffleElements(Mask, WidenedMask))
10100     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10101                                     DAG);
10102
10103   if (isSingleInputShuffleMask(Mask)) {
10104     // Check for being able to broadcast a single element.
10105     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10106                                                           Mask, Subtarget, DAG))
10107       return Broadcast;
10108
10109     // Use low duplicate instructions for masks that match their pattern.
10110     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10111       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10112
10113     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10114       // Non-half-crossing single input shuffles can be lowerid with an
10115       // interleaved permutation.
10116       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10117                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10118       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10119                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10120     }
10121
10122     // With AVX2 we have direct support for this permutation.
10123     if (Subtarget->hasAVX2())
10124       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10125                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10126
10127     // Otherwise, fall back.
10128     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10129                                                    DAG);
10130   }
10131
10132   // X86 has dedicated unpack instructions that can handle specific blend
10133   // operations: UNPCKH and UNPCKL.
10134   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10135     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10136   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10137     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10138   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10139     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10140   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10141     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10142
10143   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10144                                                 Subtarget, DAG))
10145     return Blend;
10146
10147   // Check if the blend happens to exactly fit that of SHUFPD.
10148   if (SDValue Op =
10149       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10150     return Op;
10151
10152   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10153   // shuffle. However, if we have AVX2 and either inputs are already in place,
10154   // we will be able to shuffle even across lanes the other input in a single
10155   // instruction so skip this pattern.
10156   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10157                                  isShuffleMaskInputInPlace(1, Mask))))
10158     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10159             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10160       return Result;
10161
10162   // If we have AVX2 then we always want to lower with a blend because an v4 we
10163   // can fully permute the elements.
10164   if (Subtarget->hasAVX2())
10165     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10166                                                       Mask, DAG);
10167
10168   // Otherwise fall back on generic lowering.
10169   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10170 }
10171
10172 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10173 ///
10174 /// This routine is only called when we have AVX2 and thus a reasonable
10175 /// instruction set for v4i64 shuffling..
10176 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10177                                        const X86Subtarget *Subtarget,
10178                                        SelectionDAG &DAG) {
10179   SDLoc DL(Op);
10180   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10181   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10182   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10183   ArrayRef<int> Mask = SVOp->getMask();
10184   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10185   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10186
10187   SmallVector<int, 4> WidenedMask;
10188   if (canWidenShuffleElements(Mask, WidenedMask))
10189     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10190                                     DAG);
10191
10192   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10193                                                 Subtarget, DAG))
10194     return Blend;
10195
10196   // Check for being able to broadcast a single element.
10197   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10198                                                         Mask, Subtarget, DAG))
10199     return Broadcast;
10200
10201   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10202   // use lower latency instructions that will operate on both 128-bit lanes.
10203   SmallVector<int, 2> RepeatedMask;
10204   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10205     if (isSingleInputShuffleMask(Mask)) {
10206       int PSHUFDMask[] = {-1, -1, -1, -1};
10207       for (int i = 0; i < 2; ++i)
10208         if (RepeatedMask[i] >= 0) {
10209           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10210           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10211         }
10212       return DAG.getBitcast(
10213           MVT::v4i64,
10214           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10215                       DAG.getBitcast(MVT::v8i32, V1),
10216                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10217     }
10218   }
10219
10220   // AVX2 provides a direct instruction for permuting a single input across
10221   // lanes.
10222   if (isSingleInputShuffleMask(Mask))
10223     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10224                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10225
10226   // Try to use shift instructions.
10227   if (SDValue Shift =
10228           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10229     return Shift;
10230
10231   // Use dedicated unpack instructions for masks that match their pattern.
10232   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10233     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10234   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10235     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10236   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10237     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10238   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10239     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10240
10241   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10242   // shuffle. However, if we have AVX2 and either inputs are already in place,
10243   // we will be able to shuffle even across lanes the other input in a single
10244   // instruction so skip this pattern.
10245   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10246                                  isShuffleMaskInputInPlace(1, Mask))))
10247     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10248             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10249       return Result;
10250
10251   // Otherwise fall back on generic blend lowering.
10252   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10253                                                     Mask, DAG);
10254 }
10255
10256 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10257 ///
10258 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10259 /// isn't available.
10260 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10261                                        const X86Subtarget *Subtarget,
10262                                        SelectionDAG &DAG) {
10263   SDLoc DL(Op);
10264   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10265   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10266   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10267   ArrayRef<int> Mask = SVOp->getMask();
10268   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10269
10270   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10271                                                 Subtarget, DAG))
10272     return Blend;
10273
10274   // Check for being able to broadcast a single element.
10275   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10276                                                         Mask, Subtarget, DAG))
10277     return Broadcast;
10278
10279   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10280   // options to efficiently lower the shuffle.
10281   SmallVector<int, 4> RepeatedMask;
10282   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10283     assert(RepeatedMask.size() == 4 &&
10284            "Repeated masks must be half the mask width!");
10285
10286     // Use even/odd duplicate instructions for masks that match their pattern.
10287     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10288       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10289     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10290       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10291
10292     if (isSingleInputShuffleMask(Mask))
10293       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10294                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10295
10296     // Use dedicated unpack instructions for masks that match their pattern.
10297     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10298       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10299     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10300       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10301     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10302       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10303     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10304       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10305
10306     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10307     // have already handled any direct blends. We also need to squash the
10308     // repeated mask into a simulated v4f32 mask.
10309     for (int i = 0; i < 4; ++i)
10310       if (RepeatedMask[i] >= 8)
10311         RepeatedMask[i] -= 4;
10312     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10313   }
10314
10315   // If we have a single input shuffle with different shuffle patterns in the
10316   // two 128-bit lanes use the variable mask to VPERMILPS.
10317   if (isSingleInputShuffleMask(Mask)) {
10318     SDValue VPermMask[8];
10319     for (int i = 0; i < 8; ++i)
10320       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10321                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10322     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10323       return DAG.getNode(
10324           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10325           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10326
10327     if (Subtarget->hasAVX2())
10328       return DAG.getNode(
10329           X86ISD::VPERMV, DL, MVT::v8f32,
10330           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10331                                                  MVT::v8i32, VPermMask)),
10332           V1);
10333
10334     // Otherwise, fall back.
10335     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10336                                                    DAG);
10337   }
10338
10339   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10340   // shuffle.
10341   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10342           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10343     return Result;
10344
10345   // If we have AVX2 then we always want to lower with a blend because at v8 we
10346   // can fully permute the elements.
10347   if (Subtarget->hasAVX2())
10348     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10349                                                       Mask, DAG);
10350
10351   // Otherwise fall back on generic lowering.
10352   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10353 }
10354
10355 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10356 ///
10357 /// This routine is only called when we have AVX2 and thus a reasonable
10358 /// instruction set for v8i32 shuffling..
10359 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10360                                        const X86Subtarget *Subtarget,
10361                                        SelectionDAG &DAG) {
10362   SDLoc DL(Op);
10363   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10364   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10365   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10366   ArrayRef<int> Mask = SVOp->getMask();
10367   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10368   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10369
10370   // Whenever we can lower this as a zext, that instruction is strictly faster
10371   // than any alternative. It also allows us to fold memory operands into the
10372   // shuffle in many cases.
10373   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10374                                                          Mask, Subtarget, DAG))
10375     return ZExt;
10376
10377   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10378                                                 Subtarget, DAG))
10379     return Blend;
10380
10381   // Check for being able to broadcast a single element.
10382   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10383                                                         Mask, Subtarget, DAG))
10384     return Broadcast;
10385
10386   // If the shuffle mask is repeated in each 128-bit lane we can use more
10387   // efficient instructions that mirror the shuffles across the two 128-bit
10388   // lanes.
10389   SmallVector<int, 4> RepeatedMask;
10390   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10391     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10392     if (isSingleInputShuffleMask(Mask))
10393       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10394                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10395
10396     // Use dedicated unpack instructions for masks that match their pattern.
10397     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10398       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10399     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10400       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10401     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10402       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10403     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10404       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10405   }
10406
10407   // Try to use shift instructions.
10408   if (SDValue Shift =
10409           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10410     return Shift;
10411
10412   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10413           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10414     return Rotate;
10415
10416   // If the shuffle patterns aren't repeated but it is a single input, directly
10417   // generate a cross-lane VPERMD instruction.
10418   if (isSingleInputShuffleMask(Mask)) {
10419     SDValue VPermMask[8];
10420     for (int i = 0; i < 8; ++i)
10421       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10422                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10423     return DAG.getNode(
10424         X86ISD::VPERMV, DL, MVT::v8i32,
10425         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10426   }
10427
10428   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10429   // shuffle.
10430   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10431           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10432     return Result;
10433
10434   // Otherwise fall back on generic blend lowering.
10435   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10436                                                     Mask, DAG);
10437 }
10438
10439 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10440 ///
10441 /// This routine is only called when we have AVX2 and thus a reasonable
10442 /// instruction set for v16i16 shuffling..
10443 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10444                                         const X86Subtarget *Subtarget,
10445                                         SelectionDAG &DAG) {
10446   SDLoc DL(Op);
10447   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10448   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10449   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10450   ArrayRef<int> Mask = SVOp->getMask();
10451   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10452   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10453
10454   // Whenever we can lower this as a zext, that instruction is strictly faster
10455   // than any alternative. It also allows us to fold memory operands into the
10456   // shuffle in many cases.
10457   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10458                                                          Mask, Subtarget, DAG))
10459     return ZExt;
10460
10461   // Check for being able to broadcast a single element.
10462   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10463                                                         Mask, Subtarget, DAG))
10464     return Broadcast;
10465
10466   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10467                                                 Subtarget, DAG))
10468     return Blend;
10469
10470   // Use dedicated unpack instructions for masks that match their pattern.
10471   if (isShuffleEquivalent(V1, V2, Mask,
10472                           {// First 128-bit lane:
10473                            0, 16, 1, 17, 2, 18, 3, 19,
10474                            // Second 128-bit lane:
10475                            8, 24, 9, 25, 10, 26, 11, 27}))
10476     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10477   if (isShuffleEquivalent(V1, V2, Mask,
10478                           {// First 128-bit lane:
10479                            4, 20, 5, 21, 6, 22, 7, 23,
10480                            // Second 128-bit lane:
10481                            12, 28, 13, 29, 14, 30, 15, 31}))
10482     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10483
10484   // Try to use shift instructions.
10485   if (SDValue Shift =
10486           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10487     return Shift;
10488
10489   // Try to use byte rotation instructions.
10490   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10491           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10492     return Rotate;
10493
10494   if (isSingleInputShuffleMask(Mask)) {
10495     // There are no generalized cross-lane shuffle operations available on i16
10496     // element types.
10497     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10498       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10499                                                      Mask, DAG);
10500
10501     SmallVector<int, 8> RepeatedMask;
10502     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10503       // As this is a single-input shuffle, the repeated mask should be
10504       // a strictly valid v8i16 mask that we can pass through to the v8i16
10505       // lowering to handle even the v16 case.
10506       return lowerV8I16GeneralSingleInputVectorShuffle(
10507           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10508     }
10509
10510     SDValue PSHUFBMask[32];
10511     for (int i = 0; i < 16; ++i) {
10512       if (Mask[i] == -1) {
10513         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10514         continue;
10515       }
10516
10517       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10518       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10519       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10520       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10521     }
10522     return DAG.getBitcast(MVT::v16i16,
10523                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10524                                       DAG.getBitcast(MVT::v32i8, V1),
10525                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10526                                                   MVT::v32i8, PSHUFBMask)));
10527   }
10528
10529   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10530   // shuffle.
10531   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10532           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10533     return Result;
10534
10535   // Otherwise fall back on generic lowering.
10536   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10537 }
10538
10539 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10540 ///
10541 /// This routine is only called when we have AVX2 and thus a reasonable
10542 /// instruction set for v32i8 shuffling..
10543 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10544                                        const X86Subtarget *Subtarget,
10545                                        SelectionDAG &DAG) {
10546   SDLoc DL(Op);
10547   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10548   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10549   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10550   ArrayRef<int> Mask = SVOp->getMask();
10551   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10552   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10553
10554   // Whenever we can lower this as a zext, that instruction is strictly faster
10555   // than any alternative. It also allows us to fold memory operands into the
10556   // shuffle in many cases.
10557   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10558                                                          Mask, Subtarget, DAG))
10559     return ZExt;
10560
10561   // Check for being able to broadcast a single element.
10562   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10563                                                         Mask, Subtarget, DAG))
10564     return Broadcast;
10565
10566   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10567                                                 Subtarget, DAG))
10568     return Blend;
10569
10570   // Use dedicated unpack instructions for masks that match their pattern.
10571   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10572   // 256-bit lanes.
10573   if (isShuffleEquivalent(
10574           V1, V2, Mask,
10575           {// First 128-bit lane:
10576            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10577            // Second 128-bit lane:
10578            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10579     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10580   if (isShuffleEquivalent(
10581           V1, V2, Mask,
10582           {// First 128-bit lane:
10583            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10584            // Second 128-bit lane:
10585            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10586     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10587
10588   // Try to use shift instructions.
10589   if (SDValue Shift =
10590           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10591     return Shift;
10592
10593   // Try to use byte rotation instructions.
10594   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10595           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10596     return Rotate;
10597
10598   if (isSingleInputShuffleMask(Mask)) {
10599     // There are no generalized cross-lane shuffle operations available on i8
10600     // element types.
10601     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10602       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10603                                                      Mask, DAG);
10604
10605     SDValue PSHUFBMask[32];
10606     for (int i = 0; i < 32; ++i)
10607       PSHUFBMask[i] =
10608           Mask[i] < 0
10609               ? DAG.getUNDEF(MVT::i8)
10610               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10611                                 MVT::i8);
10612
10613     return DAG.getNode(
10614         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10615         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10616   }
10617
10618   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10619   // shuffle.
10620   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10621           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10622     return Result;
10623
10624   // Otherwise fall back on generic lowering.
10625   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10626 }
10627
10628 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10629 ///
10630 /// This routine either breaks down the specific type of a 256-bit x86 vector
10631 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10632 /// together based on the available instructions.
10633 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10634                                         MVT VT, const X86Subtarget *Subtarget,
10635                                         SelectionDAG &DAG) {
10636   SDLoc DL(Op);
10637   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10638   ArrayRef<int> Mask = SVOp->getMask();
10639
10640   // If we have a single input to the zero element, insert that into V1 if we
10641   // can do so cheaply.
10642   int NumElts = VT.getVectorNumElements();
10643   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10644     return M >= NumElts;
10645   });
10646
10647   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10648     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10649                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10650       return Insertion;
10651
10652   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10653   // can check for those subtargets here and avoid much of the subtarget
10654   // querying in the per-vector-type lowering routines. With AVX1 we have
10655   // essentially *zero* ability to manipulate a 256-bit vector with integer
10656   // types. Since we'll use floating point types there eventually, just
10657   // immediately cast everything to a float and operate entirely in that domain.
10658   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10659     int ElementBits = VT.getScalarSizeInBits();
10660     if (ElementBits < 32)
10661       // No floating point type available, decompose into 128-bit vectors.
10662       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10663
10664     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10665                                 VT.getVectorNumElements());
10666     V1 = DAG.getBitcast(FpVT, V1);
10667     V2 = DAG.getBitcast(FpVT, V2);
10668     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10669   }
10670
10671   switch (VT.SimpleTy) {
10672   case MVT::v4f64:
10673     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10674   case MVT::v4i64:
10675     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10676   case MVT::v8f32:
10677     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10678   case MVT::v8i32:
10679     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10680   case MVT::v16i16:
10681     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10682   case MVT::v32i8:
10683     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10684
10685   default:
10686     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10687   }
10688 }
10689
10690 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10691                                            ArrayRef<int> Mask, SDValue V1,
10692                                            SDValue V2, SelectionDAG &DAG) {
10693
10694   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10695
10696   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10697   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10698
10699   SmallVector<SDValue, 32>  VPermMask;
10700   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10701     VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10702                         DAG.getConstant(Mask[i], DL, MaskEltVT));
10703   SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10704                                  VPermMask);
10705   if (isSingleInputShuffleMask(Mask))
10706     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10707
10708   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10709 }
10710
10711 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10712 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10713                                        const X86Subtarget *Subtarget,
10714                                        SelectionDAG &DAG) {
10715   SDLoc DL(Op);
10716   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10717   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10719   ArrayRef<int> Mask = SVOp->getMask();
10720   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10721
10722   if (SDValue Unpck =
10723           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10724     return Unpck;
10725
10726   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10727 }
10728
10729 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10730 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10731                                        const X86Subtarget *Subtarget,
10732                                        SelectionDAG &DAG) {
10733   SDLoc DL(Op);
10734   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10735   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10736   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10737   ArrayRef<int> Mask = SVOp->getMask();
10738   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10739
10740   if (SDValue Unpck =
10741           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10742     return Unpck;
10743
10744   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10745 }
10746
10747 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10748 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10749                                        const X86Subtarget *Subtarget,
10750                                        SelectionDAG &DAG) {
10751   SDLoc DL(Op);
10752   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10753   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10754   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10755   ArrayRef<int> Mask = SVOp->getMask();
10756   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10757
10758   if (SDValue Unpck =
10759           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10760     return Unpck;
10761
10762   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10763 }
10764
10765 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10766 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10767                                        const X86Subtarget *Subtarget,
10768                                        SelectionDAG &DAG) {
10769   SDLoc DL(Op);
10770   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10771   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10772   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10773   ArrayRef<int> Mask = SVOp->getMask();
10774   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10775
10776   if (SDValue Unpck =
10777           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10778     return Unpck;
10779
10780   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10781 }
10782
10783 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10784 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10785                                         const X86Subtarget *Subtarget,
10786                                         SelectionDAG &DAG) {
10787   SDLoc DL(Op);
10788   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10789   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10790   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10791   ArrayRef<int> Mask = SVOp->getMask();
10792   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10793   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10794
10795   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10796 }
10797
10798 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10799 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10800                                        const X86Subtarget *Subtarget,
10801                                        SelectionDAG &DAG) {
10802   SDLoc DL(Op);
10803   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10804   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10805   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10806   ArrayRef<int> Mask = SVOp->getMask();
10807   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10808   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10809
10810   // FIXME: Implement direct support for this type!
10811   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10812 }
10813
10814 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10815 ///
10816 /// This routine either breaks down the specific type of a 512-bit x86 vector
10817 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10818 /// together based on the available instructions.
10819 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10820                                         MVT VT, const X86Subtarget *Subtarget,
10821                                         SelectionDAG &DAG) {
10822   SDLoc DL(Op);
10823   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10824   ArrayRef<int> Mask = SVOp->getMask();
10825   assert(Subtarget->hasAVX512() &&
10826          "Cannot lower 512-bit vectors w/ basic ISA!");
10827
10828   // Check for being able to broadcast a single element.
10829   if (SDValue Broadcast =
10830           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10831     return Broadcast;
10832
10833   // Dispatch to each element type for lowering. If we don't have supprot for
10834   // specific element type shuffles at 512 bits, immediately split them and
10835   // lower them. Each lowering routine of a given type is allowed to assume that
10836   // the requisite ISA extensions for that element type are available.
10837   switch (VT.SimpleTy) {
10838   case MVT::v8f64:
10839     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10840   case MVT::v16f32:
10841     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10842   case MVT::v8i64:
10843     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10844   case MVT::v16i32:
10845     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10846   case MVT::v32i16:
10847     if (Subtarget->hasBWI())
10848       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10849     break;
10850   case MVT::v64i8:
10851     if (Subtarget->hasBWI())
10852       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10853     break;
10854
10855   default:
10856     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10857   }
10858
10859   // Otherwise fall back on splitting.
10860   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10861 }
10862
10863 // Lower vXi1 vector shuffles.
10864 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10865 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10866 // vector, shuffle and then truncate it back.
10867 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10868                                       MVT VT, const X86Subtarget *Subtarget,
10869                                       SelectionDAG &DAG) {
10870   SDLoc DL(Op);
10871   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10872   ArrayRef<int> Mask = SVOp->getMask();
10873   assert(Subtarget->hasAVX512() &&
10874          "Cannot lower 512-bit vectors w/o basic ISA!");
10875   EVT ExtVT;
10876   switch (VT.SimpleTy) {
10877   default:
10878     assert(false && "Expected a vector of i1 elements");
10879     break;
10880   case MVT::v2i1:
10881     ExtVT = MVT::v2i64;
10882     break;
10883   case MVT::v4i1:
10884     ExtVT = MVT::v4i32;
10885     break;
10886   case MVT::v8i1:
10887     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10888     break;
10889   case MVT::v16i1:
10890     ExtVT = MVT::v16i32;
10891     break;
10892   case MVT::v32i1:
10893     ExtVT = MVT::v32i16;
10894     break;
10895   case MVT::v64i1:
10896     ExtVT = MVT::v64i8;
10897     break;
10898   }
10899
10900   if (ISD::isBuildVectorAllZeros(V1.getNode()))
10901     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10902   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10903     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10904   else
10905     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10906
10907   if (V2.isUndef())
10908     V2 = DAG.getUNDEF(ExtVT);
10909   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10910     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10911   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10912     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10913   else
10914     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10915   return DAG.getNode(ISD::TRUNCATE, DL, VT,
10916                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10917 }
10918 /// \brief Top-level lowering for x86 vector shuffles.
10919 ///
10920 /// This handles decomposition, canonicalization, and lowering of all x86
10921 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10922 /// above in helper routines. The canonicalization attempts to widen shuffles
10923 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10924 /// s.t. only one of the two inputs needs to be tested, etc.
10925 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10926                                   SelectionDAG &DAG) {
10927   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10928   ArrayRef<int> Mask = SVOp->getMask();
10929   SDValue V1 = Op.getOperand(0);
10930   SDValue V2 = Op.getOperand(1);
10931   MVT VT = Op.getSimpleValueType();
10932   int NumElements = VT.getVectorNumElements();
10933   SDLoc dl(Op);
10934   bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10935
10936   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10937          "Can't lower MMX shuffles");
10938
10939   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10940   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10941   if (V1IsUndef && V2IsUndef)
10942     return DAG.getUNDEF(VT);
10943
10944   // When we create a shuffle node we put the UNDEF node to second operand,
10945   // but in some cases the first operand may be transformed to UNDEF.
10946   // In this case we should just commute the node.
10947   if (V1IsUndef)
10948     return DAG.getCommutedVectorShuffle(*SVOp);
10949
10950   // Check for non-undef masks pointing at an undef vector and make the masks
10951   // undef as well. This makes it easier to match the shuffle based solely on
10952   // the mask.
10953   if (V2IsUndef)
10954     for (int M : Mask)
10955       if (M >= NumElements) {
10956         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10957         for (int &M : NewMask)
10958           if (M >= NumElements)
10959             M = -1;
10960         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10961       }
10962
10963   // We actually see shuffles that are entirely re-arrangements of a set of
10964   // zero inputs. This mostly happens while decomposing complex shuffles into
10965   // simple ones. Directly lower these as a buildvector of zeros.
10966   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10967   if (Zeroable.all())
10968     return getZeroVector(VT, Subtarget, DAG, dl);
10969
10970   // Try to collapse shuffles into using a vector type with fewer elements but
10971   // wider element types. We cap this to not form integers or floating point
10972   // elements wider than 64 bits, but it might be interesting to form i128
10973   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10974   SmallVector<int, 16> WidenedMask;
10975   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
10976       canWidenShuffleElements(Mask, WidenedMask)) {
10977     MVT NewEltVT = VT.isFloatingPoint()
10978                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10979                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10980     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10981     // Make sure that the new vector type is legal. For example, v2f64 isn't
10982     // legal on SSE1.
10983     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10984       V1 = DAG.getBitcast(NewVT, V1);
10985       V2 = DAG.getBitcast(NewVT, V2);
10986       return DAG.getBitcast(
10987           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10988     }
10989   }
10990
10991   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10992   for (int M : SVOp->getMask())
10993     if (M < 0)
10994       ++NumUndefElements;
10995     else if (M < NumElements)
10996       ++NumV1Elements;
10997     else
10998       ++NumV2Elements;
10999
11000   // Commute the shuffle as needed such that more elements come from V1 than
11001   // V2. This allows us to match the shuffle pattern strictly on how many
11002   // elements come from V1 without handling the symmetric cases.
11003   if (NumV2Elements > NumV1Elements)
11004     return DAG.getCommutedVectorShuffle(*SVOp);
11005
11006   // When the number of V1 and V2 elements are the same, try to minimize the
11007   // number of uses of V2 in the low half of the vector. When that is tied,
11008   // ensure that the sum of indices for V1 is equal to or lower than the sum
11009   // indices for V2. When those are equal, try to ensure that the number of odd
11010   // indices for V1 is lower than the number of odd indices for V2.
11011   if (NumV1Elements == NumV2Elements) {
11012     int LowV1Elements = 0, LowV2Elements = 0;
11013     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11014       if (M >= NumElements)
11015         ++LowV2Elements;
11016       else if (M >= 0)
11017         ++LowV1Elements;
11018     if (LowV2Elements > LowV1Elements) {
11019       return DAG.getCommutedVectorShuffle(*SVOp);
11020     } else if (LowV2Elements == LowV1Elements) {
11021       int SumV1Indices = 0, SumV2Indices = 0;
11022       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11023         if (SVOp->getMask()[i] >= NumElements)
11024           SumV2Indices += i;
11025         else if (SVOp->getMask()[i] >= 0)
11026           SumV1Indices += i;
11027       if (SumV2Indices < SumV1Indices) {
11028         return DAG.getCommutedVectorShuffle(*SVOp);
11029       } else if (SumV2Indices == SumV1Indices) {
11030         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11031         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11032           if (SVOp->getMask()[i] >= NumElements)
11033             NumV2OddIndices += i % 2;
11034           else if (SVOp->getMask()[i] >= 0)
11035             NumV1OddIndices += i % 2;
11036         if (NumV2OddIndices < NumV1OddIndices)
11037           return DAG.getCommutedVectorShuffle(*SVOp);
11038       }
11039     }
11040   }
11041
11042   // For each vector width, delegate to a specialized lowering routine.
11043   if (VT.getSizeInBits() == 128)
11044     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11045
11046   if (VT.getSizeInBits() == 256)
11047     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11048
11049   if (VT.getSizeInBits() == 512)
11050     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11051
11052   if (Is1BitVector)
11053     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11054   llvm_unreachable("Unimplemented!");
11055 }
11056
11057 // This function assumes its argument is a BUILD_VECTOR of constants or
11058 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11059 // true.
11060 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11061                                     unsigned &MaskValue) {
11062   MaskValue = 0;
11063   unsigned NumElems = BuildVector->getNumOperands();
11064   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11065   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11066   unsigned NumElemsInLane = NumElems / NumLanes;
11067
11068   // Blend for v16i16 should be symmetric for the both lanes.
11069   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11070     SDValue EltCond = BuildVector->getOperand(i);
11071     SDValue SndLaneEltCond =
11072         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11073
11074     int Lane1Cond = -1, Lane2Cond = -1;
11075     if (isa<ConstantSDNode>(EltCond))
11076       Lane1Cond = !isZero(EltCond);
11077     if (isa<ConstantSDNode>(SndLaneEltCond))
11078       Lane2Cond = !isZero(SndLaneEltCond);
11079
11080     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11081       // Lane1Cond != 0, means we want the first argument.
11082       // Lane1Cond == 0, means we want the second argument.
11083       // The encoding of this argument is 0 for the first argument, 1
11084       // for the second. Therefore, invert the condition.
11085       MaskValue |= !Lane1Cond << i;
11086     else if (Lane1Cond < 0)
11087       MaskValue |= !Lane2Cond << i;
11088     else
11089       return false;
11090   }
11091   return true;
11092 }
11093
11094 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11095 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11096                                            const X86Subtarget *Subtarget,
11097                                            SelectionDAG &DAG) {
11098   SDValue Cond = Op.getOperand(0);
11099   SDValue LHS = Op.getOperand(1);
11100   SDValue RHS = Op.getOperand(2);
11101   SDLoc dl(Op);
11102   MVT VT = Op.getSimpleValueType();
11103
11104   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11105     return SDValue();
11106   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11107
11108   // Only non-legal VSELECTs reach this lowering, convert those into generic
11109   // shuffles and re-use the shuffle lowering path for blends.
11110   SmallVector<int, 32> Mask;
11111   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11112     SDValue CondElt = CondBV->getOperand(i);
11113     Mask.push_back(
11114         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11115   }
11116   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11117 }
11118
11119 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11120   // A vselect where all conditions and data are constants can be optimized into
11121   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11122   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11123       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11124       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11125     return SDValue();
11126
11127   // Try to lower this to a blend-style vector shuffle. This can handle all
11128   // constant condition cases.
11129   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11130     return BlendOp;
11131
11132   // Variable blends are only legal from SSE4.1 onward.
11133   if (!Subtarget->hasSSE41())
11134     return SDValue();
11135
11136   // Only some types will be legal on some subtargets. If we can emit a legal
11137   // VSELECT-matching blend, return Op, and but if we need to expand, return
11138   // a null value.
11139   switch (Op.getSimpleValueType().SimpleTy) {
11140   default:
11141     // Most of the vector types have blends past SSE4.1.
11142     return Op;
11143
11144   case MVT::v32i8:
11145     // The byte blends for AVX vectors were introduced only in AVX2.
11146     if (Subtarget->hasAVX2())
11147       return Op;
11148
11149     return SDValue();
11150
11151   case MVT::v8i16:
11152   case MVT::v16i16:
11153     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11154     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11155       return Op;
11156
11157     // FIXME: We should custom lower this by fixing the condition and using i8
11158     // blends.
11159     return SDValue();
11160   }
11161 }
11162
11163 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11164   MVT VT = Op.getSimpleValueType();
11165   SDLoc dl(Op);
11166
11167   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11168     return SDValue();
11169
11170   if (VT.getSizeInBits() == 8) {
11171     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11172                                   Op.getOperand(0), Op.getOperand(1));
11173     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11174                                   DAG.getValueType(VT));
11175     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11176   }
11177
11178   if (VT.getSizeInBits() == 16) {
11179     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11180     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11181     if (Idx == 0)
11182       return DAG.getNode(
11183           ISD::TRUNCATE, dl, MVT::i16,
11184           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11185                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11186                       Op.getOperand(1)));
11187     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11188                                   Op.getOperand(0), Op.getOperand(1));
11189     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11190                                   DAG.getValueType(VT));
11191     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11192   }
11193
11194   if (VT == MVT::f32) {
11195     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11196     // the result back to FR32 register. It's only worth matching if the
11197     // result has a single use which is a store or a bitcast to i32.  And in
11198     // the case of a store, it's not worth it if the index is a constant 0,
11199     // because a MOVSSmr can be used instead, which is smaller and faster.
11200     if (!Op.hasOneUse())
11201       return SDValue();
11202     SDNode *User = *Op.getNode()->use_begin();
11203     if ((User->getOpcode() != ISD::STORE ||
11204          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11205           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11206         (User->getOpcode() != ISD::BITCAST ||
11207          User->getValueType(0) != MVT::i32))
11208       return SDValue();
11209     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11210                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11211                                   Op.getOperand(1));
11212     return DAG.getBitcast(MVT::f32, Extract);
11213   }
11214
11215   if (VT == MVT::i32 || VT == MVT::i64) {
11216     // ExtractPS/pextrq works with constant index.
11217     if (isa<ConstantSDNode>(Op.getOperand(1)))
11218       return Op;
11219   }
11220   return SDValue();
11221 }
11222
11223 /// Extract one bit from mask vector, like v16i1 or v8i1.
11224 /// AVX-512 feature.
11225 SDValue
11226 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11227   SDValue Vec = Op.getOperand(0);
11228   SDLoc dl(Vec);
11229   MVT VecVT = Vec.getSimpleValueType();
11230   SDValue Idx = Op.getOperand(1);
11231   MVT EltVT = Op.getSimpleValueType();
11232
11233   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11234   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11235          "Unexpected vector type in ExtractBitFromMaskVector");
11236
11237   // variable index can't be handled in mask registers,
11238   // extend vector to VR512
11239   if (!isa<ConstantSDNode>(Idx)) {
11240     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11241     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11242     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11243                               ExtVT.getVectorElementType(), Ext, Idx);
11244     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11245   }
11246
11247   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11248   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11249   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11250     rc = getRegClassFor(MVT::v16i1);
11251   unsigned MaxSift = rc->getSize()*8 - 1;
11252   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11253                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11254   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11255                     DAG.getConstant(MaxSift, dl, MVT::i8));
11256   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11257                        DAG.getIntPtrConstant(0, dl));
11258 }
11259
11260 SDValue
11261 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11262                                            SelectionDAG &DAG) const {
11263   SDLoc dl(Op);
11264   SDValue Vec = Op.getOperand(0);
11265   MVT VecVT = Vec.getSimpleValueType();
11266   SDValue Idx = Op.getOperand(1);
11267
11268   if (Op.getSimpleValueType() == MVT::i1)
11269     return ExtractBitFromMaskVector(Op, DAG);
11270
11271   if (!isa<ConstantSDNode>(Idx)) {
11272     if (VecVT.is512BitVector() ||
11273         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11274          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11275
11276       MVT MaskEltVT =
11277         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11278       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11279                                     MaskEltVT.getSizeInBits());
11280
11281       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11282       auto PtrVT = getPointerTy(DAG.getDataLayout());
11283       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11284                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11285                                  DAG.getConstant(0, dl, PtrVT));
11286       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11287       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11288                          DAG.getConstant(0, dl, PtrVT));
11289     }
11290     return SDValue();
11291   }
11292
11293   // If this is a 256-bit vector result, first extract the 128-bit vector and
11294   // then extract the element from the 128-bit vector.
11295   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11296
11297     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11298     // Get the 128-bit vector.
11299     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11300     MVT EltVT = VecVT.getVectorElementType();
11301
11302     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11303
11304     //if (IdxVal >= NumElems/2)
11305     //  IdxVal -= NumElems/2;
11306     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11307     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11308                        DAG.getConstant(IdxVal, dl, MVT::i32));
11309   }
11310
11311   assert(VecVT.is128BitVector() && "Unexpected vector length");
11312
11313   if (Subtarget->hasSSE41())
11314     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11315       return Res;
11316
11317   MVT VT = Op.getSimpleValueType();
11318   // TODO: handle v16i8.
11319   if (VT.getSizeInBits() == 16) {
11320     SDValue Vec = Op.getOperand(0);
11321     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11322     if (Idx == 0)
11323       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11324                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11325                                      DAG.getBitcast(MVT::v4i32, Vec),
11326                                      Op.getOperand(1)));
11327     // Transform it so it match pextrw which produces a 32-bit result.
11328     MVT EltVT = MVT::i32;
11329     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11330                                   Op.getOperand(0), Op.getOperand(1));
11331     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11332                                   DAG.getValueType(VT));
11333     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11334   }
11335
11336   if (VT.getSizeInBits() == 32) {
11337     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11338     if (Idx == 0)
11339       return Op;
11340
11341     // SHUFPS the element to the lowest double word, then movss.
11342     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11343     MVT VVT = Op.getOperand(0).getSimpleValueType();
11344     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11345                                        DAG.getUNDEF(VVT), Mask);
11346     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11347                        DAG.getIntPtrConstant(0, dl));
11348   }
11349
11350   if (VT.getSizeInBits() == 64) {
11351     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11352     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11353     //        to match extract_elt for f64.
11354     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11355     if (Idx == 0)
11356       return Op;
11357
11358     // UNPCKHPD the element to the lowest double word, then movsd.
11359     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11360     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11361     int Mask[2] = { 1, -1 };
11362     MVT VVT = Op.getOperand(0).getSimpleValueType();
11363     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11364                                        DAG.getUNDEF(VVT), Mask);
11365     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11366                        DAG.getIntPtrConstant(0, dl));
11367   }
11368
11369   return SDValue();
11370 }
11371
11372 /// Insert one bit to mask vector, like v16i1 or v8i1.
11373 /// AVX-512 feature.
11374 SDValue
11375 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11376   SDLoc dl(Op);
11377   SDValue Vec = Op.getOperand(0);
11378   SDValue Elt = Op.getOperand(1);
11379   SDValue Idx = Op.getOperand(2);
11380   MVT VecVT = Vec.getSimpleValueType();
11381
11382   if (!isa<ConstantSDNode>(Idx)) {
11383     // Non constant index. Extend source and destination,
11384     // insert element and then truncate the result.
11385     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11386     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11387     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11388       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11389       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11390     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11391   }
11392
11393   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11394   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11395   if (IdxVal)
11396     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11397                            DAG.getConstant(IdxVal, dl, MVT::i8));
11398   if (Vec.getOpcode() == ISD::UNDEF)
11399     return EltInVec;
11400   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11401 }
11402
11403 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11404                                                   SelectionDAG &DAG) const {
11405   MVT VT = Op.getSimpleValueType();
11406   MVT EltVT = VT.getVectorElementType();
11407
11408   if (EltVT == MVT::i1)
11409     return InsertBitToMaskVector(Op, DAG);
11410
11411   SDLoc dl(Op);
11412   SDValue N0 = Op.getOperand(0);
11413   SDValue N1 = Op.getOperand(1);
11414   SDValue N2 = Op.getOperand(2);
11415   if (!isa<ConstantSDNode>(N2))
11416     return SDValue();
11417   auto *N2C = cast<ConstantSDNode>(N2);
11418   unsigned IdxVal = N2C->getZExtValue();
11419
11420   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11421   // into that, and then insert the subvector back into the result.
11422   if (VT.is256BitVector() || VT.is512BitVector()) {
11423     // With a 256-bit vector, we can insert into the zero element efficiently
11424     // using a blend if we have AVX or AVX2 and the right data type.
11425     if (VT.is256BitVector() && IdxVal == 0) {
11426       // TODO: It is worthwhile to cast integer to floating point and back
11427       // and incur a domain crossing penalty if that's what we'll end up
11428       // doing anyway after extracting to a 128-bit vector.
11429       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11430           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11431         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11432         N2 = DAG.getIntPtrConstant(1, dl);
11433         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11434       }
11435     }
11436
11437     // Get the desired 128-bit vector chunk.
11438     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11439
11440     // Insert the element into the desired chunk.
11441     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11442     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11443
11444     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11445                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11446
11447     // Insert the changed part back into the bigger vector
11448     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11449   }
11450   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11451
11452   if (Subtarget->hasSSE41()) {
11453     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11454       unsigned Opc;
11455       if (VT == MVT::v8i16) {
11456         Opc = X86ISD::PINSRW;
11457       } else {
11458         assert(VT == MVT::v16i8);
11459         Opc = X86ISD::PINSRB;
11460       }
11461
11462       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11463       // argument.
11464       if (N1.getValueType() != MVT::i32)
11465         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11466       if (N2.getValueType() != MVT::i32)
11467         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11468       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11469     }
11470
11471     if (EltVT == MVT::f32) {
11472       // Bits [7:6] of the constant are the source select. This will always be
11473       //   zero here. The DAG Combiner may combine an extract_elt index into
11474       //   these bits. For example (insert (extract, 3), 2) could be matched by
11475       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11476       // Bits [5:4] of the constant are the destination select. This is the
11477       //   value of the incoming immediate.
11478       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11479       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11480
11481       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11482       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11483         // If this is an insertion of 32-bits into the low 32-bits of
11484         // a vector, we prefer to generate a blend with immediate rather
11485         // than an insertps. Blends are simpler operations in hardware and so
11486         // will always have equal or better performance than insertps.
11487         // But if optimizing for size and there's a load folding opportunity,
11488         // generate insertps because blendps does not have a 32-bit memory
11489         // operand form.
11490         N2 = DAG.getIntPtrConstant(1, dl);
11491         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11492         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11493       }
11494       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11495       // Create this as a scalar to vector..
11496       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11497       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11498     }
11499
11500     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11501       // PINSR* works with constant index.
11502       return Op;
11503     }
11504   }
11505
11506   if (EltVT == MVT::i8)
11507     return SDValue();
11508
11509   if (EltVT.getSizeInBits() == 16) {
11510     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11511     // as its second argument.
11512     if (N1.getValueType() != MVT::i32)
11513       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11514     if (N2.getValueType() != MVT::i32)
11515       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11516     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11517   }
11518   return SDValue();
11519 }
11520
11521 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11522   SDLoc dl(Op);
11523   MVT OpVT = Op.getSimpleValueType();
11524
11525   // If this is a 256-bit vector result, first insert into a 128-bit
11526   // vector and then insert into the 256-bit vector.
11527   if (!OpVT.is128BitVector()) {
11528     // Insert into a 128-bit vector.
11529     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11530     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11531                                  OpVT.getVectorNumElements() / SizeFactor);
11532
11533     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11534
11535     // Insert the 128-bit vector.
11536     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11537   }
11538
11539   if (OpVT == MVT::v1i64 &&
11540       Op.getOperand(0).getValueType() == MVT::i64)
11541     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11542
11543   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11544   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11545   return DAG.getBitcast(
11546       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11547 }
11548
11549 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11550 // a simple subregister reference or explicit instructions to grab
11551 // upper bits of a vector.
11552 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11553                                       SelectionDAG &DAG) {
11554   SDLoc dl(Op);
11555   SDValue In =  Op.getOperand(0);
11556   SDValue Idx = Op.getOperand(1);
11557   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11558   MVT ResVT   = Op.getSimpleValueType();
11559   MVT InVT    = In.getSimpleValueType();
11560
11561   if (Subtarget->hasFp256()) {
11562     if (ResVT.is128BitVector() &&
11563         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11564         isa<ConstantSDNode>(Idx)) {
11565       return Extract128BitVector(In, IdxVal, DAG, dl);
11566     }
11567     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11568         isa<ConstantSDNode>(Idx)) {
11569       return Extract256BitVector(In, IdxVal, DAG, dl);
11570     }
11571   }
11572   return SDValue();
11573 }
11574
11575 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11576 // simple superregister reference or explicit instructions to insert
11577 // the upper bits of a vector.
11578 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11579                                      SelectionDAG &DAG) {
11580   if (!Subtarget->hasAVX())
11581     return SDValue();
11582
11583   SDLoc dl(Op);
11584   SDValue Vec = Op.getOperand(0);
11585   SDValue SubVec = Op.getOperand(1);
11586   SDValue Idx = Op.getOperand(2);
11587
11588   if (!isa<ConstantSDNode>(Idx))
11589     return SDValue();
11590
11591   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11592   MVT OpVT = Op.getSimpleValueType();
11593   MVT SubVecVT = SubVec.getSimpleValueType();
11594
11595   // Fold two 16-byte subvector loads into one 32-byte load:
11596   // (insert_subvector (insert_subvector undef, (load addr), 0),
11597   //                   (load addr + 16), Elts/2)
11598   // --> load32 addr
11599   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11600       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11601       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11602     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11603     if (Idx2 && Idx2->getZExtValue() == 0) {
11604       SDValue SubVec2 = Vec.getOperand(1);
11605       // If needed, look through a bitcast to get to the load.
11606       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11607         SubVec2 = SubVec2.getOperand(0);
11608
11609       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11610         bool Fast;
11611         unsigned Alignment = FirstLd->getAlignment();
11612         unsigned AS = FirstLd->getAddressSpace();
11613         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11614         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11615                                     OpVT, AS, Alignment, &Fast) && Fast) {
11616           SDValue Ops[] = { SubVec2, SubVec };
11617           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11618             return Ld;
11619         }
11620       }
11621     }
11622   }
11623
11624   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11625       SubVecVT.is128BitVector())
11626     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11627
11628   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11629     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11630
11631   if (OpVT.getVectorElementType() == MVT::i1) {
11632     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11633       return Op;
11634     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11635     SDValue Undef = DAG.getUNDEF(OpVT);
11636     unsigned NumElems = OpVT.getVectorNumElements();
11637     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11638
11639     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11640       // Zero upper bits of the Vec
11641       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11642       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11643
11644       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11645                                  SubVec, ZeroIdx);
11646       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11647       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11648     }
11649     if (IdxVal == 0) {
11650       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11651                                  SubVec, ZeroIdx);
11652       // Zero upper bits of the Vec2
11653       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11654       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11655       // Zero lower bits of the Vec
11656       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11657       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11658       // Merge them together
11659       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11660     }
11661   }
11662   return SDValue();
11663 }
11664
11665 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11666 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11667 // one of the above mentioned nodes. It has to be wrapped because otherwise
11668 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11669 // be used to form addressing mode. These wrapped nodes will be selected
11670 // into MOV32ri.
11671 SDValue
11672 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11673   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11674
11675   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11676   // global base reg.
11677   unsigned char OpFlag = 0;
11678   unsigned WrapperKind = X86ISD::Wrapper;
11679   CodeModel::Model M = DAG.getTarget().getCodeModel();
11680
11681   if (Subtarget->isPICStyleRIPRel() &&
11682       (M == CodeModel::Small || M == CodeModel::Kernel))
11683     WrapperKind = X86ISD::WrapperRIP;
11684   else if (Subtarget->isPICStyleGOT())
11685     OpFlag = X86II::MO_GOTOFF;
11686   else if (Subtarget->isPICStyleStubPIC())
11687     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11688
11689   auto PtrVT = getPointerTy(DAG.getDataLayout());
11690   SDValue Result = DAG.getTargetConstantPool(
11691       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11692   SDLoc DL(CP);
11693   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11694   // With PIC, the address is actually $g + Offset.
11695   if (OpFlag) {
11696     Result =
11697         DAG.getNode(ISD::ADD, DL, PtrVT,
11698                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11699   }
11700
11701   return Result;
11702 }
11703
11704 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11705   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11706
11707   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11708   // global base reg.
11709   unsigned char OpFlag = 0;
11710   unsigned WrapperKind = X86ISD::Wrapper;
11711   CodeModel::Model M = DAG.getTarget().getCodeModel();
11712
11713   if (Subtarget->isPICStyleRIPRel() &&
11714       (M == CodeModel::Small || M == CodeModel::Kernel))
11715     WrapperKind = X86ISD::WrapperRIP;
11716   else if (Subtarget->isPICStyleGOT())
11717     OpFlag = X86II::MO_GOTOFF;
11718   else if (Subtarget->isPICStyleStubPIC())
11719     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11720
11721   auto PtrVT = getPointerTy(DAG.getDataLayout());
11722   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11723   SDLoc DL(JT);
11724   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11725
11726   // With PIC, the address is actually $g + Offset.
11727   if (OpFlag)
11728     Result =
11729         DAG.getNode(ISD::ADD, DL, PtrVT,
11730                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11731
11732   return Result;
11733 }
11734
11735 SDValue
11736 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11737   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11738
11739   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11740   // global base reg.
11741   unsigned char OpFlag = 0;
11742   unsigned WrapperKind = X86ISD::Wrapper;
11743   CodeModel::Model M = DAG.getTarget().getCodeModel();
11744
11745   if (Subtarget->isPICStyleRIPRel() &&
11746       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11747     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11748       OpFlag = X86II::MO_GOTPCREL;
11749     WrapperKind = X86ISD::WrapperRIP;
11750   } else if (Subtarget->isPICStyleGOT()) {
11751     OpFlag = X86II::MO_GOT;
11752   } else if (Subtarget->isPICStyleStubPIC()) {
11753     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11754   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11755     OpFlag = X86II::MO_DARWIN_NONLAZY;
11756   }
11757
11758   auto PtrVT = getPointerTy(DAG.getDataLayout());
11759   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11760
11761   SDLoc DL(Op);
11762   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11763
11764   // With PIC, the address is actually $g + Offset.
11765   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11766       !Subtarget->is64Bit()) {
11767     Result =
11768         DAG.getNode(ISD::ADD, DL, PtrVT,
11769                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11770   }
11771
11772   // For symbols that require a load from a stub to get the address, emit the
11773   // load.
11774   if (isGlobalStubReference(OpFlag))
11775     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11776                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11777                          false, false, false, 0);
11778
11779   return Result;
11780 }
11781
11782 SDValue
11783 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11784   // Create the TargetBlockAddressAddress node.
11785   unsigned char OpFlags =
11786     Subtarget->ClassifyBlockAddressReference();
11787   CodeModel::Model M = DAG.getTarget().getCodeModel();
11788   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11789   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11790   SDLoc dl(Op);
11791   auto PtrVT = getPointerTy(DAG.getDataLayout());
11792   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11793
11794   if (Subtarget->isPICStyleRIPRel() &&
11795       (M == CodeModel::Small || M == CodeModel::Kernel))
11796     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11797   else
11798     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11799
11800   // With PIC, the address is actually $g + Offset.
11801   if (isGlobalRelativeToPICBase(OpFlags)) {
11802     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11803                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11804   }
11805
11806   return Result;
11807 }
11808
11809 SDValue
11810 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11811                                       int64_t Offset, SelectionDAG &DAG) const {
11812   // Create the TargetGlobalAddress node, folding in the constant
11813   // offset if it is legal.
11814   unsigned char OpFlags =
11815       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11816   CodeModel::Model M = DAG.getTarget().getCodeModel();
11817   auto PtrVT = getPointerTy(DAG.getDataLayout());
11818   SDValue Result;
11819   if (OpFlags == X86II::MO_NO_FLAG &&
11820       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11821     // A direct static reference to a global.
11822     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11823     Offset = 0;
11824   } else {
11825     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11826   }
11827
11828   if (Subtarget->isPICStyleRIPRel() &&
11829       (M == CodeModel::Small || M == CodeModel::Kernel))
11830     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11831   else
11832     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11833
11834   // With PIC, the address is actually $g + Offset.
11835   if (isGlobalRelativeToPICBase(OpFlags)) {
11836     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11837                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11838   }
11839
11840   // For globals that require a load from a stub to get the address, emit the
11841   // load.
11842   if (isGlobalStubReference(OpFlags))
11843     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11844                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11845                          false, false, false, 0);
11846
11847   // If there was a non-zero offset that we didn't fold, create an explicit
11848   // addition for it.
11849   if (Offset != 0)
11850     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11851                          DAG.getConstant(Offset, dl, PtrVT));
11852
11853   return Result;
11854 }
11855
11856 SDValue
11857 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11858   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11859   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11860   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11861 }
11862
11863 static SDValue
11864 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11865            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11866            unsigned char OperandFlags, bool LocalDynamic = false) {
11867   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11868   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11869   SDLoc dl(GA);
11870   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11871                                            GA->getValueType(0),
11872                                            GA->getOffset(),
11873                                            OperandFlags);
11874
11875   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11876                                            : X86ISD::TLSADDR;
11877
11878   if (InFlag) {
11879     SDValue Ops[] = { Chain,  TGA, *InFlag };
11880     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11881   } else {
11882     SDValue Ops[]  = { Chain, TGA };
11883     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11884   }
11885
11886   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11887   MFI->setAdjustsStack(true);
11888   MFI->setHasCalls(true);
11889
11890   SDValue Flag = Chain.getValue(1);
11891   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11892 }
11893
11894 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11895 static SDValue
11896 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11897                                 const EVT PtrVT) {
11898   SDValue InFlag;
11899   SDLoc dl(GA);  // ? function entry point might be better
11900   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11901                                    DAG.getNode(X86ISD::GlobalBaseReg,
11902                                                SDLoc(), PtrVT), InFlag);
11903   InFlag = Chain.getValue(1);
11904
11905   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11906 }
11907
11908 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11909 static SDValue
11910 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11911                                 const EVT PtrVT) {
11912   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11913                     X86::RAX, X86II::MO_TLSGD);
11914 }
11915
11916 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11917                                            SelectionDAG &DAG,
11918                                            const EVT PtrVT,
11919                                            bool is64Bit) {
11920   SDLoc dl(GA);
11921
11922   // Get the start address of the TLS block for this module.
11923   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11924       .getInfo<X86MachineFunctionInfo>();
11925   MFI->incNumLocalDynamicTLSAccesses();
11926
11927   SDValue Base;
11928   if (is64Bit) {
11929     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11930                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11931   } else {
11932     SDValue InFlag;
11933     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11934         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11935     InFlag = Chain.getValue(1);
11936     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11937                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11938   }
11939
11940   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11941   // of Base.
11942
11943   // Build x@dtpoff.
11944   unsigned char OperandFlags = X86II::MO_DTPOFF;
11945   unsigned WrapperKind = X86ISD::Wrapper;
11946   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11947                                            GA->getValueType(0),
11948                                            GA->getOffset(), OperandFlags);
11949   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11950
11951   // Add x@dtpoff with the base.
11952   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11953 }
11954
11955 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11956 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11957                                    const EVT PtrVT, TLSModel::Model model,
11958                                    bool is64Bit, bool isPIC) {
11959   SDLoc dl(GA);
11960
11961   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11962   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11963                                                          is64Bit ? 257 : 256));
11964
11965   SDValue ThreadPointer =
11966       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11967                   MachinePointerInfo(Ptr), false, false, false, 0);
11968
11969   unsigned char OperandFlags = 0;
11970   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11971   // initialexec.
11972   unsigned WrapperKind = X86ISD::Wrapper;
11973   if (model == TLSModel::LocalExec) {
11974     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11975   } else if (model == TLSModel::InitialExec) {
11976     if (is64Bit) {
11977       OperandFlags = X86II::MO_GOTTPOFF;
11978       WrapperKind = X86ISD::WrapperRIP;
11979     } else {
11980       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11981     }
11982   } else {
11983     llvm_unreachable("Unexpected model");
11984   }
11985
11986   // emit "addl x@ntpoff,%eax" (local exec)
11987   // or "addl x@indntpoff,%eax" (initial exec)
11988   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11989   SDValue TGA =
11990       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11991                                  GA->getOffset(), OperandFlags);
11992   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11993
11994   if (model == TLSModel::InitialExec) {
11995     if (isPIC && !is64Bit) {
11996       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11997                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11998                            Offset);
11999     }
12000
12001     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12002                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12003                          false, false, false, 0);
12004   }
12005
12006   // The address of the thread local variable is the add of the thread
12007   // pointer with the offset of the variable.
12008   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12009 }
12010
12011 SDValue
12012 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12013
12014   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12015   const GlobalValue *GV = GA->getGlobal();
12016   auto PtrVT = getPointerTy(DAG.getDataLayout());
12017
12018   if (Subtarget->isTargetELF()) {
12019     if (DAG.getTarget().Options.EmulatedTLS)
12020       return LowerToTLSEmulatedModel(GA, DAG);
12021     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12022     switch (model) {
12023       case TLSModel::GeneralDynamic:
12024         if (Subtarget->is64Bit())
12025           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12026         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12027       case TLSModel::LocalDynamic:
12028         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12029                                            Subtarget->is64Bit());
12030       case TLSModel::InitialExec:
12031       case TLSModel::LocalExec:
12032         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12033                                    DAG.getTarget().getRelocationModel() ==
12034                                        Reloc::PIC_);
12035     }
12036     llvm_unreachable("Unknown TLS model.");
12037   }
12038
12039   if (Subtarget->isTargetDarwin()) {
12040     // Darwin only has one model of TLS.  Lower to that.
12041     unsigned char OpFlag = 0;
12042     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12043                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12044
12045     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12046     // global base reg.
12047     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12048                  !Subtarget->is64Bit();
12049     if (PIC32)
12050       OpFlag = X86II::MO_TLVP_PIC_BASE;
12051     else
12052       OpFlag = X86II::MO_TLVP;
12053     SDLoc DL(Op);
12054     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12055                                                 GA->getValueType(0),
12056                                                 GA->getOffset(), OpFlag);
12057     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12058
12059     // With PIC32, the address is actually $g + Offset.
12060     if (PIC32)
12061       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12062                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12063                            Offset);
12064
12065     // Lowering the machine isd will make sure everything is in the right
12066     // location.
12067     SDValue Chain = DAG.getEntryNode();
12068     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12069     SDValue Args[] = { Chain, Offset };
12070     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12071
12072     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12073     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12074     MFI->setAdjustsStack(true);
12075
12076     // And our return value (tls address) is in the standard call return value
12077     // location.
12078     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12079     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12080   }
12081
12082   if (Subtarget->isTargetKnownWindowsMSVC() ||
12083       Subtarget->isTargetWindowsGNU()) {
12084     // Just use the implicit TLS architecture
12085     // Need to generate someting similar to:
12086     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12087     //                                  ; from TEB
12088     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12089     //   mov     rcx, qword [rdx+rcx*8]
12090     //   mov     eax, .tls$:tlsvar
12091     //   [rax+rcx] contains the address
12092     // Windows 64bit: gs:0x58
12093     // Windows 32bit: fs:__tls_array
12094
12095     SDLoc dl(GA);
12096     SDValue Chain = DAG.getEntryNode();
12097
12098     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12099     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12100     // use its literal value of 0x2C.
12101     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12102                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12103                                                              256)
12104                                         : Type::getInt32PtrTy(*DAG.getContext(),
12105                                                               257));
12106
12107     SDValue TlsArray = Subtarget->is64Bit()
12108                            ? DAG.getIntPtrConstant(0x58, dl)
12109                            : (Subtarget->isTargetWindowsGNU()
12110                                   ? DAG.getIntPtrConstant(0x2C, dl)
12111                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12112
12113     SDValue ThreadPointer =
12114         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12115                     false, false, 0);
12116
12117     SDValue res;
12118     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12119       res = ThreadPointer;
12120     } else {
12121       // Load the _tls_index variable
12122       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12123       if (Subtarget->is64Bit())
12124         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12125                              MachinePointerInfo(), MVT::i32, false, false,
12126                              false, 0);
12127       else
12128         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12129                           false, false, 0);
12130
12131       auto &DL = DAG.getDataLayout();
12132       SDValue Scale =
12133           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12134       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12135
12136       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12137     }
12138
12139     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12140                       false, 0);
12141
12142     // Get the offset of start of .tls section
12143     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12144                                              GA->getValueType(0),
12145                                              GA->getOffset(), X86II::MO_SECREL);
12146     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12147
12148     // The address of the thread local variable is the add of the thread
12149     // pointer with the offset of the variable.
12150     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12151   }
12152
12153   llvm_unreachable("TLS not implemented for this target.");
12154 }
12155
12156 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12157 /// and take a 2 x i32 value to shift plus a shift amount.
12158 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12159   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12160   MVT VT = Op.getSimpleValueType();
12161   unsigned VTBits = VT.getSizeInBits();
12162   SDLoc dl(Op);
12163   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12164   SDValue ShOpLo = Op.getOperand(0);
12165   SDValue ShOpHi = Op.getOperand(1);
12166   SDValue ShAmt  = Op.getOperand(2);
12167   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12168   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12169   // during isel.
12170   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12171                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12172   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12173                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12174                        : DAG.getConstant(0, dl, VT);
12175
12176   SDValue Tmp2, Tmp3;
12177   if (Op.getOpcode() == ISD::SHL_PARTS) {
12178     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12179     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12180   } else {
12181     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12182     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12183   }
12184
12185   // If the shift amount is larger or equal than the width of a part we can't
12186   // rely on the results of shld/shrd. Insert a test and select the appropriate
12187   // values for large shift amounts.
12188   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12189                                 DAG.getConstant(VTBits, dl, MVT::i8));
12190   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12191                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12192
12193   SDValue Hi, Lo;
12194   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12195   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12196   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12197
12198   if (Op.getOpcode() == ISD::SHL_PARTS) {
12199     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12200     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12201   } else {
12202     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12203     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12204   }
12205
12206   SDValue Ops[2] = { Lo, Hi };
12207   return DAG.getMergeValues(Ops, dl);
12208 }
12209
12210 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12211                                            SelectionDAG &DAG) const {
12212   SDValue Src = Op.getOperand(0);
12213   MVT SrcVT = Src.getSimpleValueType();
12214   MVT VT = Op.getSimpleValueType();
12215   SDLoc dl(Op);
12216
12217   if (SrcVT.isVector()) {
12218     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12219       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12220                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12221                          DAG.getUNDEF(SrcVT)));
12222     }
12223     if (SrcVT.getVectorElementType() == MVT::i1) {
12224       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12225       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12226                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12227     }
12228     return SDValue();
12229   }
12230
12231   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12232          "Unknown SINT_TO_FP to lower!");
12233
12234   // These are really Legal; return the operand so the caller accepts it as
12235   // Legal.
12236   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12237     return Op;
12238   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12239       Subtarget->is64Bit()) {
12240     return Op;
12241   }
12242
12243   unsigned Size = SrcVT.getSizeInBits()/8;
12244   MachineFunction &MF = DAG.getMachineFunction();
12245   auto PtrVT = getPointerTy(MF.getDataLayout());
12246   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12247   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12248   SDValue Chain = DAG.getStore(
12249       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12250       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12251       false, 0);
12252   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12253 }
12254
12255 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12256                                      SDValue StackSlot,
12257                                      SelectionDAG &DAG) const {
12258   // Build the FILD
12259   SDLoc DL(Op);
12260   SDVTList Tys;
12261   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12262   if (useSSE)
12263     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12264   else
12265     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12266
12267   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12268
12269   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12270   MachineMemOperand *MMO;
12271   if (FI) {
12272     int SSFI = FI->getIndex();
12273     MMO = DAG.getMachineFunction().getMachineMemOperand(
12274         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12275         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12276   } else {
12277     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12278     StackSlot = StackSlot.getOperand(1);
12279   }
12280   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12281   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12282                                            X86ISD::FILD, DL,
12283                                            Tys, Ops, SrcVT, MMO);
12284
12285   if (useSSE) {
12286     Chain = Result.getValue(1);
12287     SDValue InFlag = Result.getValue(2);
12288
12289     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12290     // shouldn't be necessary except that RFP cannot be live across
12291     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12292     MachineFunction &MF = DAG.getMachineFunction();
12293     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12294     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12295     auto PtrVT = getPointerTy(MF.getDataLayout());
12296     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12297     Tys = DAG.getVTList(MVT::Other);
12298     SDValue Ops[] = {
12299       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12300     };
12301     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12302         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12303         MachineMemOperand::MOStore, SSFISize, SSFISize);
12304
12305     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12306                                     Ops, Op.getValueType(), MMO);
12307     Result = DAG.getLoad(
12308         Op.getValueType(), DL, Chain, StackSlot,
12309         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12310         false, false, false, 0);
12311   }
12312
12313   return Result;
12314 }
12315
12316 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12317 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12318                                                SelectionDAG &DAG) const {
12319   // This algorithm is not obvious. Here it is what we're trying to output:
12320   /*
12321      movq       %rax,  %xmm0
12322      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12323      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12324      #ifdef __SSE3__
12325        haddpd   %xmm0, %xmm0
12326      #else
12327        pshufd   $0x4e, %xmm0, %xmm1
12328        addpd    %xmm1, %xmm0
12329      #endif
12330   */
12331
12332   SDLoc dl(Op);
12333   LLVMContext *Context = DAG.getContext();
12334
12335   // Build some magic constants.
12336   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12337   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12338   auto PtrVT = getPointerTy(DAG.getDataLayout());
12339   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12340
12341   SmallVector<Constant*,2> CV1;
12342   CV1.push_back(
12343     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12344                                       APInt(64, 0x4330000000000000ULL))));
12345   CV1.push_back(
12346     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12347                                       APInt(64, 0x4530000000000000ULL))));
12348   Constant *C1 = ConstantVector::get(CV1);
12349   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12350
12351   // Load the 64-bit value into an XMM register.
12352   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12353                             Op.getOperand(0));
12354   SDValue CLod0 =
12355       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12356                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12357                   false, false, false, 16);
12358   SDValue Unpck1 =
12359       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12360
12361   SDValue CLod1 =
12362       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12363                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12364                   false, false, false, 16);
12365   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12366   // TODO: Are there any fast-math-flags to propagate here?
12367   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12368   SDValue Result;
12369
12370   if (Subtarget->hasSSE3()) {
12371     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12372     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12373   } else {
12374     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12375     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12376                                            S2F, 0x4E, DAG);
12377     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12378                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12379   }
12380
12381   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12382                      DAG.getIntPtrConstant(0, dl));
12383 }
12384
12385 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12386 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12387                                                SelectionDAG &DAG) const {
12388   SDLoc dl(Op);
12389   // FP constant to bias correct the final result.
12390   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12391                                    MVT::f64);
12392
12393   // Load the 32-bit value into an XMM register.
12394   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12395                              Op.getOperand(0));
12396
12397   // Zero out the upper parts of the register.
12398   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12399
12400   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12401                      DAG.getBitcast(MVT::v2f64, Load),
12402                      DAG.getIntPtrConstant(0, dl));
12403
12404   // Or the load with the bias.
12405   SDValue Or = DAG.getNode(
12406       ISD::OR, dl, MVT::v2i64,
12407       DAG.getBitcast(MVT::v2i64,
12408                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12409       DAG.getBitcast(MVT::v2i64,
12410                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12411   Or =
12412       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12413                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12414
12415   // Subtract the bias.
12416   // TODO: Are there any fast-math-flags to propagate here?
12417   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12418
12419   // Handle final rounding.
12420   EVT DestVT = Op.getValueType();
12421
12422   if (DestVT.bitsLT(MVT::f64))
12423     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12424                        DAG.getIntPtrConstant(0, dl));
12425   if (DestVT.bitsGT(MVT::f64))
12426     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12427
12428   // Handle final rounding.
12429   return Sub;
12430 }
12431
12432 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12433                                      const X86Subtarget &Subtarget) {
12434   // The algorithm is the following:
12435   // #ifdef __SSE4_1__
12436   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12437   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12438   //                                 (uint4) 0x53000000, 0xaa);
12439   // #else
12440   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12441   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12442   // #endif
12443   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12444   //     return (float4) lo + fhi;
12445
12446   SDLoc DL(Op);
12447   SDValue V = Op->getOperand(0);
12448   EVT VecIntVT = V.getValueType();
12449   bool Is128 = VecIntVT == MVT::v4i32;
12450   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12451   // If we convert to something else than the supported type, e.g., to v4f64,
12452   // abort early.
12453   if (VecFloatVT != Op->getValueType(0))
12454     return SDValue();
12455
12456   unsigned NumElts = VecIntVT.getVectorNumElements();
12457   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12458          "Unsupported custom type");
12459   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12460
12461   // In the #idef/#else code, we have in common:
12462   // - The vector of constants:
12463   // -- 0x4b000000
12464   // -- 0x53000000
12465   // - A shift:
12466   // -- v >> 16
12467
12468   // Create the splat vector for 0x4b000000.
12469   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12470   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12471                            CstLow, CstLow, CstLow, CstLow};
12472   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12473                                   makeArrayRef(&CstLowArray[0], NumElts));
12474   // Create the splat vector for 0x53000000.
12475   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12476   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12477                             CstHigh, CstHigh, CstHigh, CstHigh};
12478   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12479                                    makeArrayRef(&CstHighArray[0], NumElts));
12480
12481   // Create the right shift.
12482   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12483   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12484                              CstShift, CstShift, CstShift, CstShift};
12485   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12486                                     makeArrayRef(&CstShiftArray[0], NumElts));
12487   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12488
12489   SDValue Low, High;
12490   if (Subtarget.hasSSE41()) {
12491     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12492     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12493     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12494     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12495     // Low will be bitcasted right away, so do not bother bitcasting back to its
12496     // original type.
12497     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12498                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12499     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12500     //                                 (uint4) 0x53000000, 0xaa);
12501     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12502     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12503     // High will be bitcasted right away, so do not bother bitcasting back to
12504     // its original type.
12505     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12506                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12507   } else {
12508     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12509     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12510                                      CstMask, CstMask, CstMask);
12511     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12512     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12513     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12514
12515     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12516     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12517   }
12518
12519   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12520   SDValue CstFAdd = DAG.getConstantFP(
12521       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12522   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12523                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12524   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12525                                    makeArrayRef(&CstFAddArray[0], NumElts));
12526
12527   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12528   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12529   // TODO: Are there any fast-math-flags to propagate here?
12530   SDValue FHigh =
12531       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12532   //     return (float4) lo + fhi;
12533   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12534   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12535 }
12536
12537 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12538                                                SelectionDAG &DAG) const {
12539   SDValue N0 = Op.getOperand(0);
12540   MVT SVT = N0.getSimpleValueType();
12541   SDLoc dl(Op);
12542
12543   switch (SVT.SimpleTy) {
12544   default:
12545     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12546   case MVT::v4i8:
12547   case MVT::v4i16:
12548   case MVT::v8i8:
12549   case MVT::v8i16: {
12550     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12551     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12552                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12553   }
12554   case MVT::v4i32:
12555   case MVT::v8i32:
12556     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12557   case MVT::v16i8:
12558   case MVT::v16i16:
12559     if (Subtarget->hasAVX512())
12560       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12561                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12562   }
12563   llvm_unreachable(nullptr);
12564 }
12565
12566 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12567                                            SelectionDAG &DAG) const {
12568   SDValue N0 = Op.getOperand(0);
12569   SDLoc dl(Op);
12570   auto PtrVT = getPointerTy(DAG.getDataLayout());
12571
12572   if (Op.getValueType().isVector())
12573     return lowerUINT_TO_FP_vec(Op, DAG);
12574
12575   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12576   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12577   // the optimization here.
12578   if (DAG.SignBitIsZero(N0))
12579     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12580
12581   MVT SrcVT = N0.getSimpleValueType();
12582   MVT DstVT = Op.getSimpleValueType();
12583
12584   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12585       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12586     // Conversions from unsigned i32 to f32/f64 are legal,
12587     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12588     return Op;
12589   }
12590
12591   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12592     return LowerUINT_TO_FP_i64(Op, DAG);
12593   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12594     return LowerUINT_TO_FP_i32(Op, DAG);
12595   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12596     return SDValue();
12597
12598   // Make a 64-bit buffer, and use it to build an FILD.
12599   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12600   if (SrcVT == MVT::i32) {
12601     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12602     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12603     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12604                                   StackSlot, MachinePointerInfo(),
12605                                   false, false, 0);
12606     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12607                                   OffsetSlot, MachinePointerInfo(),
12608                                   false, false, 0);
12609     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12610     return Fild;
12611   }
12612
12613   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12614   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12615                                StackSlot, MachinePointerInfo(),
12616                                false, false, 0);
12617   // For i64 source, we need to add the appropriate power of 2 if the input
12618   // was negative.  This is the same as the optimization in
12619   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12620   // we must be careful to do the computation in x87 extended precision, not
12621   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12622   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12623   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12624       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12625       MachineMemOperand::MOLoad, 8, 8);
12626
12627   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12628   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12629   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12630                                          MVT::i64, MMO);
12631
12632   APInt FF(32, 0x5F800000ULL);
12633
12634   // Check whether the sign bit is set.
12635   SDValue SignSet = DAG.getSetCC(
12636       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12637       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12638
12639   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12640   SDValue FudgePtr = DAG.getConstantPool(
12641       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12642
12643   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12644   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12645   SDValue Four = DAG.getIntPtrConstant(4, dl);
12646   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12647                                Zero, Four);
12648   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12649
12650   // Load the value out, extending it from f32 to f80.
12651   // FIXME: Avoid the extend by constructing the right constant pool?
12652   SDValue Fudge = DAG.getExtLoad(
12653       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12654       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12655       false, false, false, 4);
12656   // Extend everything to 80 bits to force it to be done on x87.
12657   // TODO: Are there any fast-math-flags to propagate here?
12658   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12659   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12660                      DAG.getIntPtrConstant(0, dl));
12661 }
12662
12663 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12664 // is legal, or has an f16 source (which needs to be promoted to f32),
12665 // just return an <SDValue(), SDValue()> pair.
12666 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12667 // to i16, i32 or i64, and we lower it to a legal sequence.
12668 // If lowered to the final integer result we return a <result, SDValue()> pair.
12669 // Otherwise we lower it to a sequence ending with a FIST, return a
12670 // <FIST, StackSlot> pair, and the caller is responsible for loading
12671 // the final integer result from StackSlot.
12672 std::pair<SDValue,SDValue>
12673 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12674                                    bool IsSigned, bool IsReplace) const {
12675   SDLoc DL(Op);
12676
12677   EVT DstTy = Op.getValueType();
12678   EVT TheVT = Op.getOperand(0).getValueType();
12679   auto PtrVT = getPointerTy(DAG.getDataLayout());
12680
12681   if (TheVT == MVT::f16)
12682     // We need to promote the f16 to f32 before using the lowering
12683     // in this routine.
12684     return std::make_pair(SDValue(), SDValue());
12685
12686   assert((TheVT == MVT::f32 ||
12687           TheVT == MVT::f64 ||
12688           TheVT == MVT::f80) &&
12689          "Unexpected FP operand type in FP_TO_INTHelper");
12690
12691   // If using FIST to compute an unsigned i64, we'll need some fixup
12692   // to handle values above the maximum signed i64.  A FIST is always
12693   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12694   bool UnsignedFixup = !IsSigned &&
12695                        DstTy == MVT::i64 &&
12696                        (!Subtarget->is64Bit() ||
12697                         !isScalarFPTypeInSSEReg(TheVT));
12698
12699   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12700     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12701     // The low 32 bits of the fist result will have the correct uint32 result.
12702     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12703     DstTy = MVT::i64;
12704   }
12705
12706   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12707          DstTy.getSimpleVT() >= MVT::i16 &&
12708          "Unknown FP_TO_INT to lower!");
12709
12710   // These are really Legal.
12711   if (DstTy == MVT::i32 &&
12712       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12713     return std::make_pair(SDValue(), SDValue());
12714   if (Subtarget->is64Bit() &&
12715       DstTy == MVT::i64 &&
12716       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12717     return std::make_pair(SDValue(), SDValue());
12718
12719   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12720   // stack slot.
12721   MachineFunction &MF = DAG.getMachineFunction();
12722   unsigned MemSize = DstTy.getSizeInBits()/8;
12723   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12724   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12725
12726   unsigned Opc;
12727   switch (DstTy.getSimpleVT().SimpleTy) {
12728   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12729   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12730   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12731   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12732   }
12733
12734   SDValue Chain = DAG.getEntryNode();
12735   SDValue Value = Op.getOperand(0);
12736   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12737
12738   if (UnsignedFixup) {
12739     //
12740     // Conversion to unsigned i64 is implemented with a select,
12741     // depending on whether the source value fits in the range
12742     // of a signed i64.  Let Thresh be the FP equivalent of
12743     // 0x8000000000000000ULL.
12744     //
12745     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12746     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12747     //  Fist-to-mem64 FistSrc
12748     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12749     //  to XOR'ing the high 32 bits with Adjust.
12750     //
12751     // Being a power of 2, Thresh is exactly representable in all FP formats.
12752     // For X87 we'd like to use the smallest FP type for this constant, but
12753     // for DAG type consistency we have to match the FP operand type.
12754
12755     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12756     APFloat::opStatus Status = APFloat::opOK;
12757     bool LosesInfo = false;
12758     if (TheVT == MVT::f64)
12759       // The rounding mode is irrelevant as the conversion should be exact.
12760       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12761                               &LosesInfo);
12762     else if (TheVT == MVT::f80)
12763       Status = Thresh.convert(APFloat::x87DoubleExtended,
12764                               APFloat::rmNearestTiesToEven, &LosesInfo);
12765
12766     assert(Status == APFloat::opOK && !LosesInfo &&
12767            "FP conversion should have been exact");
12768
12769     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12770
12771     SDValue Cmp = DAG.getSetCC(DL,
12772                                getSetCCResultType(DAG.getDataLayout(),
12773                                                   *DAG.getContext(), TheVT),
12774                                Value, ThreshVal, ISD::SETLT);
12775     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12776                            DAG.getConstant(0, DL, MVT::i32),
12777                            DAG.getConstant(0x80000000, DL, MVT::i32));
12778     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12779     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12780                                               *DAG.getContext(), TheVT),
12781                        Value, ThreshVal, ISD::SETLT);
12782     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12783   }
12784
12785   // FIXME This causes a redundant load/store if the SSE-class value is already
12786   // in memory, such as if it is on the callstack.
12787   if (isScalarFPTypeInSSEReg(TheVT)) {
12788     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12789     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12790                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12791                          false, 0);
12792     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12793     SDValue Ops[] = {
12794       Chain, StackSlot, DAG.getValueType(TheVT)
12795     };
12796
12797     MachineMemOperand *MMO =
12798         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12799                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12800     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12801     Chain = Value.getValue(1);
12802     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12803     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12804   }
12805
12806   MachineMemOperand *MMO =
12807       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12808                               MachineMemOperand::MOStore, MemSize, MemSize);
12809
12810   if (UnsignedFixup) {
12811
12812     // Insert the FIST, load its result as two i32's,
12813     // and XOR the high i32 with Adjust.
12814
12815     SDValue FistOps[] = { Chain, Value, StackSlot };
12816     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12817                                            FistOps, DstTy, MMO);
12818
12819     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12820                                 MachinePointerInfo(),
12821                                 false, false, false, 0);
12822     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12823                                    DAG.getConstant(4, DL, PtrVT));
12824
12825     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12826                                  MachinePointerInfo(),
12827                                  false, false, false, 0);
12828     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12829
12830     if (Subtarget->is64Bit()) {
12831       // Join High32 and Low32 into a 64-bit result.
12832       // (High32 << 32) | Low32
12833       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12834       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12835       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12836                            DAG.getConstant(32, DL, MVT::i8));
12837       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12838       return std::make_pair(Result, SDValue());
12839     }
12840
12841     SDValue ResultOps[] = { Low32, High32 };
12842
12843     SDValue pair = IsReplace
12844       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12845       : DAG.getMergeValues(ResultOps, DL);
12846     return std::make_pair(pair, SDValue());
12847   } else {
12848     // Build the FP_TO_INT*_IN_MEM
12849     SDValue Ops[] = { Chain, Value, StackSlot };
12850     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12851                                            Ops, DstTy, MMO);
12852     return std::make_pair(FIST, StackSlot);
12853   }
12854 }
12855
12856 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12857                               const X86Subtarget *Subtarget) {
12858   MVT VT = Op->getSimpleValueType(0);
12859   SDValue In = Op->getOperand(0);
12860   MVT InVT = In.getSimpleValueType();
12861   SDLoc dl(Op);
12862
12863   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12864     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12865
12866   // Optimize vectors in AVX mode:
12867   //
12868   //   v8i16 -> v8i32
12869   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12870   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12871   //   Concat upper and lower parts.
12872   //
12873   //   v4i32 -> v4i64
12874   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12875   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12876   //   Concat upper and lower parts.
12877   //
12878
12879   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12880       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12881       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12882     return SDValue();
12883
12884   if (Subtarget->hasInt256())
12885     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12886
12887   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12888   SDValue Undef = DAG.getUNDEF(InVT);
12889   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12890   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12891   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12892
12893   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12894                              VT.getVectorNumElements()/2);
12895
12896   OpLo = DAG.getBitcast(HVT, OpLo);
12897   OpHi = DAG.getBitcast(HVT, OpHi);
12898
12899   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12900 }
12901
12902 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12903                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12904   MVT VT = Op->getSimpleValueType(0);
12905   SDValue In = Op->getOperand(0);
12906   MVT InVT = In.getSimpleValueType();
12907   SDLoc DL(Op);
12908   unsigned int NumElts = VT.getVectorNumElements();
12909   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12910     return SDValue();
12911
12912   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12913     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12914
12915   assert(InVT.getVectorElementType() == MVT::i1);
12916   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12917   SDValue One =
12918    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12919   SDValue Zero =
12920    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12921
12922   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12923   if (VT.is512BitVector())
12924     return V;
12925   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12926 }
12927
12928 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12929                                SelectionDAG &DAG) {
12930   if (Subtarget->hasFp256())
12931     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12932       return Res;
12933
12934   return SDValue();
12935 }
12936
12937 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12938                                 SelectionDAG &DAG) {
12939   SDLoc DL(Op);
12940   MVT VT = Op.getSimpleValueType();
12941   SDValue In = Op.getOperand(0);
12942   MVT SVT = In.getSimpleValueType();
12943
12944   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12945     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12946
12947   if (Subtarget->hasFp256())
12948     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12949       return Res;
12950
12951   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12952          VT.getVectorNumElements() != SVT.getVectorNumElements());
12953   return SDValue();
12954 }
12955
12956 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12957   SDLoc DL(Op);
12958   MVT VT = Op.getSimpleValueType();
12959   SDValue In = Op.getOperand(0);
12960   MVT InVT = In.getSimpleValueType();
12961
12962   if (VT == MVT::i1) {
12963     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12964            "Invalid scalar TRUNCATE operation");
12965     if (InVT.getSizeInBits() >= 32)
12966       return SDValue();
12967     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12968     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12969   }
12970   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12971          "Invalid TRUNCATE operation");
12972
12973   // move vector to mask - truncate solution for SKX
12974   if (VT.getVectorElementType() == MVT::i1) {
12975     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12976         Subtarget->hasBWI())
12977       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12978     if ((InVT.is256BitVector() || InVT.is128BitVector())
12979         && InVT.getScalarSizeInBits() <= 16 &&
12980         Subtarget->hasBWI() && Subtarget->hasVLX())
12981       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12982     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12983         Subtarget->hasDQI())
12984       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12985     if ((InVT.is256BitVector() || InVT.is128BitVector())
12986         && InVT.getScalarSizeInBits() >= 32 &&
12987         Subtarget->hasDQI() && Subtarget->hasVLX())
12988       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12989   }
12990
12991   if (VT.getVectorElementType() == MVT::i1) {
12992     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12993     unsigned NumElts = InVT.getVectorNumElements();
12994     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12995     if (InVT.getSizeInBits() < 512) {
12996       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12997       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12998       InVT = ExtVT;
12999     }
13000
13001     SDValue OneV =
13002      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13003     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13004     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13005   }
13006
13007   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13008   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13009       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13010     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13011
13012   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13013     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13014     if (Subtarget->hasInt256()) {
13015       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13016       In = DAG.getBitcast(MVT::v8i32, In);
13017       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13018                                 ShufMask);
13019       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13020                          DAG.getIntPtrConstant(0, DL));
13021     }
13022
13023     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13024                                DAG.getIntPtrConstant(0, DL));
13025     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13026                                DAG.getIntPtrConstant(2, DL));
13027     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13028     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13029     static const int ShufMask[] = {0, 2, 4, 6};
13030     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13031   }
13032
13033   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13034     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13035     if (Subtarget->hasInt256()) {
13036       In = DAG.getBitcast(MVT::v32i8, In);
13037
13038       SmallVector<SDValue,32> pshufbMask;
13039       for (unsigned i = 0; i < 2; ++i) {
13040         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13041         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13042         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13043         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13044         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13045         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13046         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13047         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13048         for (unsigned j = 0; j < 8; ++j)
13049           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13050       }
13051       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13052       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13053       In = DAG.getBitcast(MVT::v4i64, In);
13054
13055       static const int ShufMask[] = {0,  2,  -1,  -1};
13056       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13057                                 &ShufMask[0]);
13058       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13059                        DAG.getIntPtrConstant(0, DL));
13060       return DAG.getBitcast(VT, In);
13061     }
13062
13063     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13064                                DAG.getIntPtrConstant(0, DL));
13065
13066     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13067                                DAG.getIntPtrConstant(4, DL));
13068
13069     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13070     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13071
13072     // The PSHUFB mask:
13073     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13074                                    -1, -1, -1, -1, -1, -1, -1, -1};
13075
13076     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13077     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13078     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13079
13080     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13081     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13082
13083     // The MOVLHPS Mask:
13084     static const int ShufMask2[] = {0, 1, 4, 5};
13085     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13086     return DAG.getBitcast(MVT::v8i16, res);
13087   }
13088
13089   // Handle truncation of V256 to V128 using shuffles.
13090   if (!VT.is128BitVector() || !InVT.is256BitVector())
13091     return SDValue();
13092
13093   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13094
13095   unsigned NumElems = VT.getVectorNumElements();
13096   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13097
13098   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13099   // Prepare truncation shuffle mask
13100   for (unsigned i = 0; i != NumElems; ++i)
13101     MaskVec[i] = i * 2;
13102   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13103                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13104   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13105                      DAG.getIntPtrConstant(0, DL));
13106 }
13107
13108 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13109                                            SelectionDAG &DAG) const {
13110   assert(!Op.getSimpleValueType().isVector());
13111
13112   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13113     /*IsSigned=*/ true, /*IsReplace=*/ false);
13114   SDValue FIST = Vals.first, StackSlot = Vals.second;
13115   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13116   if (!FIST.getNode())
13117     return Op;
13118
13119   if (StackSlot.getNode())
13120     // Load the result.
13121     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13122                        FIST, StackSlot, MachinePointerInfo(),
13123                        false, false, false, 0);
13124
13125   // The node is the result.
13126   return FIST;
13127 }
13128
13129 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13130                                            SelectionDAG &DAG) const {
13131   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13132     /*IsSigned=*/ false, /*IsReplace=*/ false);
13133   SDValue FIST = Vals.first, StackSlot = Vals.second;
13134   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13135   if (!FIST.getNode())
13136     return Op;
13137
13138   if (StackSlot.getNode())
13139     // Load the result.
13140     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13141                        FIST, StackSlot, MachinePointerInfo(),
13142                        false, false, false, 0);
13143
13144   // The node is the result.
13145   return FIST;
13146 }
13147
13148 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13149   SDLoc DL(Op);
13150   MVT VT = Op.getSimpleValueType();
13151   SDValue In = Op.getOperand(0);
13152   MVT SVT = In.getSimpleValueType();
13153
13154   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13155
13156   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13157                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13158                                  In, DAG.getUNDEF(SVT)));
13159 }
13160
13161 /// The only differences between FABS and FNEG are the mask and the logic op.
13162 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13163 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13164   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13165          "Wrong opcode for lowering FABS or FNEG.");
13166
13167   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13168
13169   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13170   // into an FNABS. We'll lower the FABS after that if it is still in use.
13171   if (IsFABS)
13172     for (SDNode *User : Op->uses())
13173       if (User->getOpcode() == ISD::FNEG)
13174         return Op;
13175
13176   SDLoc dl(Op);
13177   MVT VT = Op.getSimpleValueType();
13178
13179   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13180   // decide if we should generate a 16-byte constant mask when we only need 4 or
13181   // 8 bytes for the scalar case.
13182
13183   MVT LogicVT;
13184   MVT EltVT;
13185   unsigned NumElts;
13186
13187   if (VT.isVector()) {
13188     LogicVT = VT;
13189     EltVT = VT.getVectorElementType();
13190     NumElts = VT.getVectorNumElements();
13191   } else {
13192     // There are no scalar bitwise logical SSE/AVX instructions, so we
13193     // generate a 16-byte vector constant and logic op even for the scalar case.
13194     // Using a 16-byte mask allows folding the load of the mask with
13195     // the logic op, so it can save (~4 bytes) on code size.
13196     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13197     EltVT = VT;
13198     NumElts = (VT == MVT::f64) ? 2 : 4;
13199   }
13200
13201   unsigned EltBits = EltVT.getSizeInBits();
13202   LLVMContext *Context = DAG.getContext();
13203   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13204   APInt MaskElt =
13205     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13206   Constant *C = ConstantInt::get(*Context, MaskElt);
13207   C = ConstantVector::getSplat(NumElts, C);
13208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13209   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13210   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13211   SDValue Mask =
13212       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13213                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13214                   false, false, false, Alignment);
13215
13216   SDValue Op0 = Op.getOperand(0);
13217   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13218   unsigned LogicOp =
13219     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13220   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13221
13222   if (VT.isVector())
13223     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13224
13225   // For the scalar case extend to a 128-bit vector, perform the logic op,
13226   // and extract the scalar result back out.
13227   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13228   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13229   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13230                      DAG.getIntPtrConstant(0, dl));
13231 }
13232
13233 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13234   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13235   LLVMContext *Context = DAG.getContext();
13236   SDValue Op0 = Op.getOperand(0);
13237   SDValue Op1 = Op.getOperand(1);
13238   SDLoc dl(Op);
13239   MVT VT = Op.getSimpleValueType();
13240   MVT SrcVT = Op1.getSimpleValueType();
13241
13242   // If second operand is smaller, extend it first.
13243   if (SrcVT.bitsLT(VT)) {
13244     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13245     SrcVT = VT;
13246   }
13247   // And if it is bigger, shrink it first.
13248   if (SrcVT.bitsGT(VT)) {
13249     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13250     SrcVT = VT;
13251   }
13252
13253   // At this point the operands and the result should have the same
13254   // type, and that won't be f80 since that is not custom lowered.
13255
13256   const fltSemantics &Sem =
13257       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13258   const unsigned SizeInBits = VT.getSizeInBits();
13259
13260   SmallVector<Constant *, 4> CV(
13261       VT == MVT::f64 ? 2 : 4,
13262       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13263
13264   // First, clear all bits but the sign bit from the second operand (sign).
13265   CV[0] = ConstantFP::get(*Context,
13266                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13267   Constant *C = ConstantVector::get(CV);
13268   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13269   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13270
13271   // Perform all logic operations as 16-byte vectors because there are no
13272   // scalar FP logic instructions in SSE. This allows load folding of the
13273   // constants into the logic instructions.
13274   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13275   SDValue Mask1 =
13276       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13277                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13278                   false, false, false, 16);
13279   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13280   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13281
13282   // Next, clear the sign bit from the first operand (magnitude).
13283   // If it's a constant, we can clear it here.
13284   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13285     APFloat APF = Op0CN->getValueAPF();
13286     // If the magnitude is a positive zero, the sign bit alone is enough.
13287     if (APF.isPosZero())
13288       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13289                          DAG.getIntPtrConstant(0, dl));
13290     APF.clearSign();
13291     CV[0] = ConstantFP::get(*Context, APF);
13292   } else {
13293     CV[0] = ConstantFP::get(
13294         *Context,
13295         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13296   }
13297   C = ConstantVector::get(CV);
13298   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13299   SDValue Val =
13300       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13301                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13302                   false, false, false, 16);
13303   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13304   if (!isa<ConstantFPSDNode>(Op0)) {
13305     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13306     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13307   }
13308   // OR the magnitude value with the sign bit.
13309   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13310   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13311                      DAG.getIntPtrConstant(0, dl));
13312 }
13313
13314 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13315   SDValue N0 = Op.getOperand(0);
13316   SDLoc dl(Op);
13317   MVT VT = Op.getSimpleValueType();
13318
13319   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13320   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13321                                   DAG.getConstant(1, dl, VT));
13322   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13323 }
13324
13325 // Check whether an OR'd tree is PTEST-able.
13326 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13327                                       SelectionDAG &DAG) {
13328   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13329
13330   if (!Subtarget->hasSSE41())
13331     return SDValue();
13332
13333   if (!Op->hasOneUse())
13334     return SDValue();
13335
13336   SDNode *N = Op.getNode();
13337   SDLoc DL(N);
13338
13339   SmallVector<SDValue, 8> Opnds;
13340   DenseMap<SDValue, unsigned> VecInMap;
13341   SmallVector<SDValue, 8> VecIns;
13342   EVT VT = MVT::Other;
13343
13344   // Recognize a special case where a vector is casted into wide integer to
13345   // test all 0s.
13346   Opnds.push_back(N->getOperand(0));
13347   Opnds.push_back(N->getOperand(1));
13348
13349   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13350     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13351     // BFS traverse all OR'd operands.
13352     if (I->getOpcode() == ISD::OR) {
13353       Opnds.push_back(I->getOperand(0));
13354       Opnds.push_back(I->getOperand(1));
13355       // Re-evaluate the number of nodes to be traversed.
13356       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13357       continue;
13358     }
13359
13360     // Quit if a non-EXTRACT_VECTOR_ELT
13361     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13362       return SDValue();
13363
13364     // Quit if without a constant index.
13365     SDValue Idx = I->getOperand(1);
13366     if (!isa<ConstantSDNode>(Idx))
13367       return SDValue();
13368
13369     SDValue ExtractedFromVec = I->getOperand(0);
13370     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13371     if (M == VecInMap.end()) {
13372       VT = ExtractedFromVec.getValueType();
13373       // Quit if not 128/256-bit vector.
13374       if (!VT.is128BitVector() && !VT.is256BitVector())
13375         return SDValue();
13376       // Quit if not the same type.
13377       if (VecInMap.begin() != VecInMap.end() &&
13378           VT != VecInMap.begin()->first.getValueType())
13379         return SDValue();
13380       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13381       VecIns.push_back(ExtractedFromVec);
13382     }
13383     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13384   }
13385
13386   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13387          "Not extracted from 128-/256-bit vector.");
13388
13389   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13390
13391   for (DenseMap<SDValue, unsigned>::const_iterator
13392         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13393     // Quit if not all elements are used.
13394     if (I->second != FullMask)
13395       return SDValue();
13396   }
13397
13398   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13399
13400   // Cast all vectors into TestVT for PTEST.
13401   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13402     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13403
13404   // If more than one full vectors are evaluated, OR them first before PTEST.
13405   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13406     // Each iteration will OR 2 nodes and append the result until there is only
13407     // 1 node left, i.e. the final OR'd value of all vectors.
13408     SDValue LHS = VecIns[Slot];
13409     SDValue RHS = VecIns[Slot + 1];
13410     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13411   }
13412
13413   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13414                      VecIns.back(), VecIns.back());
13415 }
13416
13417 /// \brief return true if \c Op has a use that doesn't just read flags.
13418 static bool hasNonFlagsUse(SDValue Op) {
13419   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13420        ++UI) {
13421     SDNode *User = *UI;
13422     unsigned UOpNo = UI.getOperandNo();
13423     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13424       // Look pass truncate.
13425       UOpNo = User->use_begin().getOperandNo();
13426       User = *User->use_begin();
13427     }
13428
13429     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13430         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13431       return true;
13432   }
13433   return false;
13434 }
13435
13436 /// Emit nodes that will be selected as "test Op0,Op0", or something
13437 /// equivalent.
13438 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13439                                     SelectionDAG &DAG) const {
13440   if (Op.getValueType() == MVT::i1) {
13441     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13442     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13443                        DAG.getConstant(0, dl, MVT::i8));
13444   }
13445   // CF and OF aren't always set the way we want. Determine which
13446   // of these we need.
13447   bool NeedCF = false;
13448   bool NeedOF = false;
13449   switch (X86CC) {
13450   default: break;
13451   case X86::COND_A: case X86::COND_AE:
13452   case X86::COND_B: case X86::COND_BE:
13453     NeedCF = true;
13454     break;
13455   case X86::COND_G: case X86::COND_GE:
13456   case X86::COND_L: case X86::COND_LE:
13457   case X86::COND_O: case X86::COND_NO: {
13458     // Check if we really need to set the
13459     // Overflow flag. If NoSignedWrap is present
13460     // that is not actually needed.
13461     switch (Op->getOpcode()) {
13462     case ISD::ADD:
13463     case ISD::SUB:
13464     case ISD::MUL:
13465     case ISD::SHL: {
13466       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13467       if (BinNode->Flags.hasNoSignedWrap())
13468         break;
13469     }
13470     default:
13471       NeedOF = true;
13472       break;
13473     }
13474     break;
13475   }
13476   }
13477   // See if we can use the EFLAGS value from the operand instead of
13478   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13479   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13480   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13481     // Emit a CMP with 0, which is the TEST pattern.
13482     //if (Op.getValueType() == MVT::i1)
13483     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13484     //                     DAG.getConstant(0, MVT::i1));
13485     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13486                        DAG.getConstant(0, dl, Op.getValueType()));
13487   }
13488   unsigned Opcode = 0;
13489   unsigned NumOperands = 0;
13490
13491   // Truncate operations may prevent the merge of the SETCC instruction
13492   // and the arithmetic instruction before it. Attempt to truncate the operands
13493   // of the arithmetic instruction and use a reduced bit-width instruction.
13494   bool NeedTruncation = false;
13495   SDValue ArithOp = Op;
13496   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13497     SDValue Arith = Op->getOperand(0);
13498     // Both the trunc and the arithmetic op need to have one user each.
13499     if (Arith->hasOneUse())
13500       switch (Arith.getOpcode()) {
13501         default: break;
13502         case ISD::ADD:
13503         case ISD::SUB:
13504         case ISD::AND:
13505         case ISD::OR:
13506         case ISD::XOR: {
13507           NeedTruncation = true;
13508           ArithOp = Arith;
13509         }
13510       }
13511   }
13512
13513   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13514   // which may be the result of a CAST.  We use the variable 'Op', which is the
13515   // non-casted variable when we check for possible users.
13516   switch (ArithOp.getOpcode()) {
13517   case ISD::ADD:
13518     // Due to an isel shortcoming, be conservative if this add is likely to be
13519     // selected as part of a load-modify-store instruction. When the root node
13520     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13521     // uses of other nodes in the match, such as the ADD in this case. This
13522     // leads to the ADD being left around and reselected, with the result being
13523     // two adds in the output.  Alas, even if none our users are stores, that
13524     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13525     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13526     // climbing the DAG back to the root, and it doesn't seem to be worth the
13527     // effort.
13528     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13529          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13530       if (UI->getOpcode() != ISD::CopyToReg &&
13531           UI->getOpcode() != ISD::SETCC &&
13532           UI->getOpcode() != ISD::STORE)
13533         goto default_case;
13534
13535     if (ConstantSDNode *C =
13536         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13537       // An add of one will be selected as an INC.
13538       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13539         Opcode = X86ISD::INC;
13540         NumOperands = 1;
13541         break;
13542       }
13543
13544       // An add of negative one (subtract of one) will be selected as a DEC.
13545       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13546         Opcode = X86ISD::DEC;
13547         NumOperands = 1;
13548         break;
13549       }
13550     }
13551
13552     // Otherwise use a regular EFLAGS-setting add.
13553     Opcode = X86ISD::ADD;
13554     NumOperands = 2;
13555     break;
13556   case ISD::SHL:
13557   case ISD::SRL:
13558     // If we have a constant logical shift that's only used in a comparison
13559     // against zero turn it into an equivalent AND. This allows turning it into
13560     // a TEST instruction later.
13561     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13562         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13563       EVT VT = Op.getValueType();
13564       unsigned BitWidth = VT.getSizeInBits();
13565       unsigned ShAmt = Op->getConstantOperandVal(1);
13566       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13567         break;
13568       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13569                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13570                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13571       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13572         break;
13573       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13574                                 DAG.getConstant(Mask, dl, VT));
13575       DAG.ReplaceAllUsesWith(Op, New);
13576       Op = New;
13577     }
13578     break;
13579
13580   case ISD::AND:
13581     // If the primary and result isn't used, don't bother using X86ISD::AND,
13582     // because a TEST instruction will be better.
13583     if (!hasNonFlagsUse(Op))
13584       break;
13585     // FALL THROUGH
13586   case ISD::SUB:
13587   case ISD::OR:
13588   case ISD::XOR:
13589     // Due to the ISEL shortcoming noted above, be conservative if this op is
13590     // likely to be selected as part of a load-modify-store instruction.
13591     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13592            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13593       if (UI->getOpcode() == ISD::STORE)
13594         goto default_case;
13595
13596     // Otherwise use a regular EFLAGS-setting instruction.
13597     switch (ArithOp.getOpcode()) {
13598     default: llvm_unreachable("unexpected operator!");
13599     case ISD::SUB: Opcode = X86ISD::SUB; break;
13600     case ISD::XOR: Opcode = X86ISD::XOR; break;
13601     case ISD::AND: Opcode = X86ISD::AND; break;
13602     case ISD::OR: {
13603       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13604         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13605         if (EFLAGS.getNode())
13606           return EFLAGS;
13607       }
13608       Opcode = X86ISD::OR;
13609       break;
13610     }
13611     }
13612
13613     NumOperands = 2;
13614     break;
13615   case X86ISD::ADD:
13616   case X86ISD::SUB:
13617   case X86ISD::INC:
13618   case X86ISD::DEC:
13619   case X86ISD::OR:
13620   case X86ISD::XOR:
13621   case X86ISD::AND:
13622     return SDValue(Op.getNode(), 1);
13623   default:
13624   default_case:
13625     break;
13626   }
13627
13628   // If we found that truncation is beneficial, perform the truncation and
13629   // update 'Op'.
13630   if (NeedTruncation) {
13631     EVT VT = Op.getValueType();
13632     SDValue WideVal = Op->getOperand(0);
13633     EVT WideVT = WideVal.getValueType();
13634     unsigned ConvertedOp = 0;
13635     // Use a target machine opcode to prevent further DAGCombine
13636     // optimizations that may separate the arithmetic operations
13637     // from the setcc node.
13638     switch (WideVal.getOpcode()) {
13639       default: break;
13640       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13641       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13642       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13643       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13644       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13645     }
13646
13647     if (ConvertedOp) {
13648       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13649       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13650         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13651         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13652         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13653       }
13654     }
13655   }
13656
13657   if (Opcode == 0)
13658     // Emit a CMP with 0, which is the TEST pattern.
13659     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13660                        DAG.getConstant(0, dl, Op.getValueType()));
13661
13662   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13663   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13664
13665   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13666   DAG.ReplaceAllUsesWith(Op, New);
13667   return SDValue(New.getNode(), 1);
13668 }
13669
13670 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13671 /// equivalent.
13672 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13673                                    SDLoc dl, SelectionDAG &DAG) const {
13674   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13675     if (C->getAPIntValue() == 0)
13676       return EmitTest(Op0, X86CC, dl, DAG);
13677
13678      if (Op0.getValueType() == MVT::i1)
13679        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13680   }
13681
13682   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13683        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13684     // Do the comparison at i32 if it's smaller, besides the Atom case.
13685     // This avoids subregister aliasing issues. Keep the smaller reference
13686     // if we're optimizing for size, however, as that'll allow better folding
13687     // of memory operations.
13688     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13689         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13690         !Subtarget->isAtom()) {
13691       unsigned ExtendOp =
13692           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13693       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13694       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13695     }
13696     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13697     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13698     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13699                               Op0, Op1);
13700     return SDValue(Sub.getNode(), 1);
13701   }
13702   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13703 }
13704
13705 /// Convert a comparison if required by the subtarget.
13706 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13707                                                  SelectionDAG &DAG) const {
13708   // If the subtarget does not support the FUCOMI instruction, floating-point
13709   // comparisons have to be converted.
13710   if (Subtarget->hasCMov() ||
13711       Cmp.getOpcode() != X86ISD::CMP ||
13712       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13713       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13714     return Cmp;
13715
13716   // The instruction selector will select an FUCOM instruction instead of
13717   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13718   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13719   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13720   SDLoc dl(Cmp);
13721   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13722   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13723   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13724                             DAG.getConstant(8, dl, MVT::i8));
13725   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13726   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13727 }
13728
13729 /// The minimum architected relative accuracy is 2^-12. We need one
13730 /// Newton-Raphson step to have a good float result (24 bits of precision).
13731 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13732                                             DAGCombinerInfo &DCI,
13733                                             unsigned &RefinementSteps,
13734                                             bool &UseOneConstNR) const {
13735   EVT VT = Op.getValueType();
13736   const char *RecipOp;
13737
13738   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13739   // TODO: Add support for AVX512 (v16f32).
13740   // It is likely not profitable to do this for f64 because a double-precision
13741   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13742   // instructions: convert to single, rsqrtss, convert back to double, refine
13743   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13744   // along with FMA, this could be a throughput win.
13745   if (VT == MVT::f32 && Subtarget->hasSSE1())
13746     RecipOp = "sqrtf";
13747   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13748            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13749     RecipOp = "vec-sqrtf";
13750   else
13751     return SDValue();
13752
13753   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13754   if (!Recips.isEnabled(RecipOp))
13755     return SDValue();
13756
13757   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13758   UseOneConstNR = false;
13759   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13760 }
13761
13762 /// The minimum architected relative accuracy is 2^-12. We need one
13763 /// Newton-Raphson step to have a good float result (24 bits of precision).
13764 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13765                                             DAGCombinerInfo &DCI,
13766                                             unsigned &RefinementSteps) const {
13767   EVT VT = Op.getValueType();
13768   const char *RecipOp;
13769
13770   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13771   // TODO: Add support for AVX512 (v16f32).
13772   // It is likely not profitable to do this for f64 because a double-precision
13773   // reciprocal estimate with refinement on x86 prior to FMA requires
13774   // 15 instructions: convert to single, rcpss, convert back to double, refine
13775   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13776   // along with FMA, this could be a throughput win.
13777   if (VT == MVT::f32 && Subtarget->hasSSE1())
13778     RecipOp = "divf";
13779   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13780            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13781     RecipOp = "vec-divf";
13782   else
13783     return SDValue();
13784
13785   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13786   if (!Recips.isEnabled(RecipOp))
13787     return SDValue();
13788
13789   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13790   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13791 }
13792
13793 /// If we have at least two divisions that use the same divisor, convert to
13794 /// multplication by a reciprocal. This may need to be adjusted for a given
13795 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13796 /// This is because we still need one division to calculate the reciprocal and
13797 /// then we need two multiplies by that reciprocal as replacements for the
13798 /// original divisions.
13799 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13800   return 2;
13801 }
13802
13803 static bool isAllOnes(SDValue V) {
13804   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13805   return C && C->isAllOnesValue();
13806 }
13807
13808 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13809 /// if it's possible.
13810 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13811                                      SDLoc dl, SelectionDAG &DAG) const {
13812   SDValue Op0 = And.getOperand(0);
13813   SDValue Op1 = And.getOperand(1);
13814   if (Op0.getOpcode() == ISD::TRUNCATE)
13815     Op0 = Op0.getOperand(0);
13816   if (Op1.getOpcode() == ISD::TRUNCATE)
13817     Op1 = Op1.getOperand(0);
13818
13819   SDValue LHS, RHS;
13820   if (Op1.getOpcode() == ISD::SHL)
13821     std::swap(Op0, Op1);
13822   if (Op0.getOpcode() == ISD::SHL) {
13823     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13824       if (And00C->getZExtValue() == 1) {
13825         // If we looked past a truncate, check that it's only truncating away
13826         // known zeros.
13827         unsigned BitWidth = Op0.getValueSizeInBits();
13828         unsigned AndBitWidth = And.getValueSizeInBits();
13829         if (BitWidth > AndBitWidth) {
13830           APInt Zeros, Ones;
13831           DAG.computeKnownBits(Op0, Zeros, Ones);
13832           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13833             return SDValue();
13834         }
13835         LHS = Op1;
13836         RHS = Op0.getOperand(1);
13837       }
13838   } else if (Op1.getOpcode() == ISD::Constant) {
13839     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13840     uint64_t AndRHSVal = AndRHS->getZExtValue();
13841     SDValue AndLHS = Op0;
13842
13843     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13844       LHS = AndLHS.getOperand(0);
13845       RHS = AndLHS.getOperand(1);
13846     }
13847
13848     // Use BT if the immediate can't be encoded in a TEST instruction.
13849     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13850       LHS = AndLHS;
13851       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13852     }
13853   }
13854
13855   if (LHS.getNode()) {
13856     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13857     // instruction.  Since the shift amount is in-range-or-undefined, we know
13858     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13859     // the encoding for the i16 version is larger than the i32 version.
13860     // Also promote i16 to i32 for performance / code size reason.
13861     if (LHS.getValueType() == MVT::i8 ||
13862         LHS.getValueType() == MVT::i16)
13863       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13864
13865     // If the operand types disagree, extend the shift amount to match.  Since
13866     // BT ignores high bits (like shifts) we can use anyextend.
13867     if (LHS.getValueType() != RHS.getValueType())
13868       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13869
13870     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13871     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13872     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13873                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13874   }
13875
13876   return SDValue();
13877 }
13878
13879 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13880 /// mask CMPs.
13881 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13882                               SDValue &Op1) {
13883   unsigned SSECC;
13884   bool Swap = false;
13885
13886   // SSE Condition code mapping:
13887   //  0 - EQ
13888   //  1 - LT
13889   //  2 - LE
13890   //  3 - UNORD
13891   //  4 - NEQ
13892   //  5 - NLT
13893   //  6 - NLE
13894   //  7 - ORD
13895   switch (SetCCOpcode) {
13896   default: llvm_unreachable("Unexpected SETCC condition");
13897   case ISD::SETOEQ:
13898   case ISD::SETEQ:  SSECC = 0; break;
13899   case ISD::SETOGT:
13900   case ISD::SETGT:  Swap = true; // Fallthrough
13901   case ISD::SETLT:
13902   case ISD::SETOLT: SSECC = 1; break;
13903   case ISD::SETOGE:
13904   case ISD::SETGE:  Swap = true; // Fallthrough
13905   case ISD::SETLE:
13906   case ISD::SETOLE: SSECC = 2; break;
13907   case ISD::SETUO:  SSECC = 3; break;
13908   case ISD::SETUNE:
13909   case ISD::SETNE:  SSECC = 4; break;
13910   case ISD::SETULE: Swap = true; // Fallthrough
13911   case ISD::SETUGE: SSECC = 5; break;
13912   case ISD::SETULT: Swap = true; // Fallthrough
13913   case ISD::SETUGT: SSECC = 6; break;
13914   case ISD::SETO:   SSECC = 7; break;
13915   case ISD::SETUEQ:
13916   case ISD::SETONE: SSECC = 8; break;
13917   }
13918   if (Swap)
13919     std::swap(Op0, Op1);
13920
13921   return SSECC;
13922 }
13923
13924 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13925 // ones, and then concatenate the result back.
13926 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13927   MVT VT = Op.getSimpleValueType();
13928
13929   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13930          "Unsupported value type for operation");
13931
13932   unsigned NumElems = VT.getVectorNumElements();
13933   SDLoc dl(Op);
13934   SDValue CC = Op.getOperand(2);
13935
13936   // Extract the LHS vectors
13937   SDValue LHS = Op.getOperand(0);
13938   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13939   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13940
13941   // Extract the RHS vectors
13942   SDValue RHS = Op.getOperand(1);
13943   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13944   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13945
13946   // Issue the operation on the smaller types and concatenate the result back
13947   MVT EltVT = VT.getVectorElementType();
13948   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13949   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13950                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13951                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13952 }
13953
13954 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13955   SDValue Op0 = Op.getOperand(0);
13956   SDValue Op1 = Op.getOperand(1);
13957   SDValue CC = Op.getOperand(2);
13958   MVT VT = Op.getSimpleValueType();
13959   SDLoc dl(Op);
13960
13961   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13962          "Unexpected type for boolean compare operation");
13963   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13964   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13965                                DAG.getConstant(-1, dl, VT));
13966   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13967                                DAG.getConstant(-1, dl, VT));
13968   switch (SetCCOpcode) {
13969   default: llvm_unreachable("Unexpected SETCC condition");
13970   case ISD::SETEQ:
13971     // (x == y) -> ~(x ^ y)
13972     return DAG.getNode(ISD::XOR, dl, VT,
13973                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13974                        DAG.getConstant(-1, dl, VT));
13975   case ISD::SETNE:
13976     // (x != y) -> (x ^ y)
13977     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13978   case ISD::SETUGT:
13979   case ISD::SETGT:
13980     // (x > y) -> (x & ~y)
13981     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13982   case ISD::SETULT:
13983   case ISD::SETLT:
13984     // (x < y) -> (~x & y)
13985     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13986   case ISD::SETULE:
13987   case ISD::SETLE:
13988     // (x <= y) -> (~x | y)
13989     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13990   case ISD::SETUGE:
13991   case ISD::SETGE:
13992     // (x >=y) -> (x | ~y)
13993     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13994   }
13995 }
13996
13997 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13998                                      const X86Subtarget *Subtarget) {
13999   SDValue Op0 = Op.getOperand(0);
14000   SDValue Op1 = Op.getOperand(1);
14001   SDValue CC = Op.getOperand(2);
14002   MVT VT = Op.getSimpleValueType();
14003   SDLoc dl(Op);
14004
14005   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14006          Op.getValueType().getScalarType() == MVT::i1 &&
14007          "Cannot set masked compare for this operation");
14008
14009   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14010   unsigned  Opc = 0;
14011   bool Unsigned = false;
14012   bool Swap = false;
14013   unsigned SSECC;
14014   switch (SetCCOpcode) {
14015   default: llvm_unreachable("Unexpected SETCC condition");
14016   case ISD::SETNE:  SSECC = 4; break;
14017   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14018   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14019   case ISD::SETLT:  Swap = true; //fall-through
14020   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14021   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14022   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14023   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14024   case ISD::SETULE: Unsigned = true; //fall-through
14025   case ISD::SETLE:  SSECC = 2; break;
14026   }
14027
14028   if (Swap)
14029     std::swap(Op0, Op1);
14030   if (Opc)
14031     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14032   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14033   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14034                      DAG.getConstant(SSECC, dl, MVT::i8));
14035 }
14036
14037 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14038 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14039 /// return an empty value.
14040 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14041 {
14042   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14043   if (!BV)
14044     return SDValue();
14045
14046   MVT VT = Op1.getSimpleValueType();
14047   MVT EVT = VT.getVectorElementType();
14048   unsigned n = VT.getVectorNumElements();
14049   SmallVector<SDValue, 8> ULTOp1;
14050
14051   for (unsigned i = 0; i < n; ++i) {
14052     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14053     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14054       return SDValue();
14055
14056     // Avoid underflow.
14057     APInt Val = Elt->getAPIntValue();
14058     if (Val == 0)
14059       return SDValue();
14060
14061     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14062   }
14063
14064   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14065 }
14066
14067 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14068                            SelectionDAG &DAG) {
14069   SDValue Op0 = Op.getOperand(0);
14070   SDValue Op1 = Op.getOperand(1);
14071   SDValue CC = Op.getOperand(2);
14072   MVT VT = Op.getSimpleValueType();
14073   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14074   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14075   SDLoc dl(Op);
14076
14077   if (isFP) {
14078 #ifndef NDEBUG
14079     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14080     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14081 #endif
14082
14083     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14084     unsigned Opc = X86ISD::CMPP;
14085     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14086       assert(VT.getVectorNumElements() <= 16);
14087       Opc = X86ISD::CMPM;
14088     }
14089     // In the two special cases we can't handle, emit two comparisons.
14090     if (SSECC == 8) {
14091       unsigned CC0, CC1;
14092       unsigned CombineOpc;
14093       if (SetCCOpcode == ISD::SETUEQ) {
14094         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14095       } else {
14096         assert(SetCCOpcode == ISD::SETONE);
14097         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14098       }
14099
14100       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14101                                  DAG.getConstant(CC0, dl, MVT::i8));
14102       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14103                                  DAG.getConstant(CC1, dl, MVT::i8));
14104       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14105     }
14106     // Handle all other FP comparisons here.
14107     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14108                        DAG.getConstant(SSECC, dl, MVT::i8));
14109   }
14110
14111   // Break 256-bit integer vector compare into smaller ones.
14112   if (VT.is256BitVector() && !Subtarget->hasInt256())
14113     return Lower256IntVSETCC(Op, DAG);
14114
14115   EVT OpVT = Op1.getValueType();
14116   if (OpVT.getVectorElementType() == MVT::i1)
14117     return LowerBoolVSETCC_AVX512(Op, DAG);
14118
14119   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14120   if (Subtarget->hasAVX512()) {
14121     if (Op1.getValueType().is512BitVector() ||
14122         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14123         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14124       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14125
14126     // In AVX-512 architecture setcc returns mask with i1 elements,
14127     // But there is no compare instruction for i8 and i16 elements in KNL.
14128     // We are not talking about 512-bit operands in this case, these
14129     // types are illegal.
14130     if (MaskResult &&
14131         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14132          OpVT.getVectorElementType().getSizeInBits() >= 8))
14133       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14134                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14135   }
14136
14137   // We are handling one of the integer comparisons here.  Since SSE only has
14138   // GT and EQ comparisons for integer, swapping operands and multiple
14139   // operations may be required for some comparisons.
14140   unsigned Opc;
14141   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14142   bool Subus = false;
14143
14144   switch (SetCCOpcode) {
14145   default: llvm_unreachable("Unexpected SETCC condition");
14146   case ISD::SETNE:  Invert = true;
14147   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14148   case ISD::SETLT:  Swap = true;
14149   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14150   case ISD::SETGE:  Swap = true;
14151   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14152                     Invert = true; break;
14153   case ISD::SETULT: Swap = true;
14154   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14155                     FlipSigns = true; break;
14156   case ISD::SETUGE: Swap = true;
14157   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14158                     FlipSigns = true; Invert = true; break;
14159   }
14160
14161   // Special case: Use min/max operations for SETULE/SETUGE
14162   MVT VET = VT.getVectorElementType();
14163   bool hasMinMax =
14164        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14165     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14166
14167   if (hasMinMax) {
14168     switch (SetCCOpcode) {
14169     default: break;
14170     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14171     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14172     }
14173
14174     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14175   }
14176
14177   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14178   if (!MinMax && hasSubus) {
14179     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14180     // Op0 u<= Op1:
14181     //   t = psubus Op0, Op1
14182     //   pcmpeq t, <0..0>
14183     switch (SetCCOpcode) {
14184     default: break;
14185     case ISD::SETULT: {
14186       // If the comparison is against a constant we can turn this into a
14187       // setule.  With psubus, setule does not require a swap.  This is
14188       // beneficial because the constant in the register is no longer
14189       // destructed as the destination so it can be hoisted out of a loop.
14190       // Only do this pre-AVX since vpcmp* is no longer destructive.
14191       if (Subtarget->hasAVX())
14192         break;
14193       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14194       if (ULEOp1.getNode()) {
14195         Op1 = ULEOp1;
14196         Subus = true; Invert = false; Swap = false;
14197       }
14198       break;
14199     }
14200     // Psubus is better than flip-sign because it requires no inversion.
14201     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14202     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14203     }
14204
14205     if (Subus) {
14206       Opc = X86ISD::SUBUS;
14207       FlipSigns = false;
14208     }
14209   }
14210
14211   if (Swap)
14212     std::swap(Op0, Op1);
14213
14214   // Check that the operation in question is available (most are plain SSE2,
14215   // but PCMPGTQ and PCMPEQQ have different requirements).
14216   if (VT == MVT::v2i64) {
14217     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14218       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14219
14220       // First cast everything to the right type.
14221       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14222       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14223
14224       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14225       // bits of the inputs before performing those operations. The lower
14226       // compare is always unsigned.
14227       SDValue SB;
14228       if (FlipSigns) {
14229         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14230       } else {
14231         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14232         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14233         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14234                          Sign, Zero, Sign, Zero);
14235       }
14236       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14237       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14238
14239       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14240       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14241       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14242
14243       // Create masks for only the low parts/high parts of the 64 bit integers.
14244       static const int MaskHi[] = { 1, 1, 3, 3 };
14245       static const int MaskLo[] = { 0, 0, 2, 2 };
14246       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14247       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14248       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14249
14250       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14251       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14252
14253       if (Invert)
14254         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14255
14256       return DAG.getBitcast(VT, Result);
14257     }
14258
14259     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14260       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14261       // pcmpeqd + pshufd + pand.
14262       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14263
14264       // First cast everything to the right type.
14265       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14266       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14267
14268       // Do the compare.
14269       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14270
14271       // Make sure the lower and upper halves are both all-ones.
14272       static const int Mask[] = { 1, 0, 3, 2 };
14273       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14274       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14275
14276       if (Invert)
14277         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14278
14279       return DAG.getBitcast(VT, Result);
14280     }
14281   }
14282
14283   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14284   // bits of the inputs before performing those operations.
14285   if (FlipSigns) {
14286     EVT EltVT = VT.getVectorElementType();
14287     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14288                                  VT);
14289     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14290     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14291   }
14292
14293   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14294
14295   // If the logical-not of the result is required, perform that now.
14296   if (Invert)
14297     Result = DAG.getNOT(dl, Result, VT);
14298
14299   if (MinMax)
14300     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14301
14302   if (Subus)
14303     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14304                          getZeroVector(VT, Subtarget, DAG, dl));
14305
14306   return Result;
14307 }
14308
14309 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14310
14311   MVT VT = Op.getSimpleValueType();
14312
14313   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14314
14315   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14316          && "SetCC type must be 8-bit or 1-bit integer");
14317   SDValue Op0 = Op.getOperand(0);
14318   SDValue Op1 = Op.getOperand(1);
14319   SDLoc dl(Op);
14320   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14321
14322   // Optimize to BT if possible.
14323   // Lower (X & (1 << N)) == 0 to BT(X, N).
14324   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14325   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14326   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14327       Op1.getOpcode() == ISD::Constant &&
14328       cast<ConstantSDNode>(Op1)->isNullValue() &&
14329       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14330     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14331     if (NewSetCC.getNode()) {
14332       if (VT == MVT::i1)
14333         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14334       return NewSetCC;
14335     }
14336   }
14337
14338   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14339   // these.
14340   if (Op1.getOpcode() == ISD::Constant &&
14341       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14342        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14343       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14344
14345     // If the input is a setcc, then reuse the input setcc or use a new one with
14346     // the inverted condition.
14347     if (Op0.getOpcode() == X86ISD::SETCC) {
14348       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14349       bool Invert = (CC == ISD::SETNE) ^
14350         cast<ConstantSDNode>(Op1)->isNullValue();
14351       if (!Invert)
14352         return Op0;
14353
14354       CCode = X86::GetOppositeBranchCondition(CCode);
14355       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14356                                   DAG.getConstant(CCode, dl, MVT::i8),
14357                                   Op0.getOperand(1));
14358       if (VT == MVT::i1)
14359         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14360       return SetCC;
14361     }
14362   }
14363   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14364       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14365       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14366
14367     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14368     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14369   }
14370
14371   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14372   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14373   if (X86CC == X86::COND_INVALID)
14374     return SDValue();
14375
14376   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14377   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14378   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14379                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14380   if (VT == MVT::i1)
14381     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14382   return SetCC;
14383 }
14384
14385 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14386 static bool isX86LogicalCmp(SDValue Op) {
14387   unsigned Opc = Op.getNode()->getOpcode();
14388   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14389       Opc == X86ISD::SAHF)
14390     return true;
14391   if (Op.getResNo() == 1 &&
14392       (Opc == X86ISD::ADD ||
14393        Opc == X86ISD::SUB ||
14394        Opc == X86ISD::ADC ||
14395        Opc == X86ISD::SBB ||
14396        Opc == X86ISD::SMUL ||
14397        Opc == X86ISD::UMUL ||
14398        Opc == X86ISD::INC ||
14399        Opc == X86ISD::DEC ||
14400        Opc == X86ISD::OR ||
14401        Opc == X86ISD::XOR ||
14402        Opc == X86ISD::AND))
14403     return true;
14404
14405   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14406     return true;
14407
14408   return false;
14409 }
14410
14411 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14412   if (V.getOpcode() != ISD::TRUNCATE)
14413     return false;
14414
14415   SDValue VOp0 = V.getOperand(0);
14416   unsigned InBits = VOp0.getValueSizeInBits();
14417   unsigned Bits = V.getValueSizeInBits();
14418   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14419 }
14420
14421 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14422   bool addTest = true;
14423   SDValue Cond  = Op.getOperand(0);
14424   SDValue Op1 = Op.getOperand(1);
14425   SDValue Op2 = Op.getOperand(2);
14426   SDLoc DL(Op);
14427   EVT VT = Op1.getValueType();
14428   SDValue CC;
14429
14430   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14431   // are available or VBLENDV if AVX is available.
14432   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14433   if (Cond.getOpcode() == ISD::SETCC &&
14434       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14435        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14436       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14437     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14438     int SSECC = translateX86FSETCC(
14439         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14440
14441     if (SSECC != 8) {
14442       if (Subtarget->hasAVX512()) {
14443         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14444                                   DAG.getConstant(SSECC, DL, MVT::i8));
14445         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14446       }
14447
14448       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14449                                 DAG.getConstant(SSECC, DL, MVT::i8));
14450
14451       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14452       // of 3 logic instructions for size savings and potentially speed.
14453       // Unfortunately, there is no scalar form of VBLENDV.
14454
14455       // If either operand is a constant, don't try this. We can expect to
14456       // optimize away at least one of the logic instructions later in that
14457       // case, so that sequence would be faster than a variable blend.
14458
14459       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14460       // uses XMM0 as the selection register. That may need just as many
14461       // instructions as the AND/ANDN/OR sequence due to register moves, so
14462       // don't bother.
14463
14464       if (Subtarget->hasAVX() &&
14465           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14466
14467         // Convert to vectors, do a VSELECT, and convert back to scalar.
14468         // All of the conversions should be optimized away.
14469
14470         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14471         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14472         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14473         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14474
14475         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14476         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14477
14478         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14479
14480         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14481                            VSel, DAG.getIntPtrConstant(0, DL));
14482       }
14483       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14484       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14485       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14486     }
14487   }
14488
14489   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14490     SDValue Op1Scalar;
14491     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14492       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14493     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14494       Op1Scalar = Op1.getOperand(0);
14495     SDValue Op2Scalar;
14496     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14497       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14498     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14499       Op2Scalar = Op2.getOperand(0);
14500     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14501       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14502                                       Op1Scalar.getValueType(),
14503                                       Cond, Op1Scalar, Op2Scalar);
14504       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14505         return DAG.getBitcast(VT, newSelect);
14506       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14507       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14508                          DAG.getIntPtrConstant(0, DL));
14509     }
14510   }
14511
14512   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14513     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14514     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14515                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14516     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14517                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14518     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14519                                     Cond, Op1, Op2);
14520     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14521   }
14522
14523   if (Cond.getOpcode() == ISD::SETCC) {
14524     SDValue NewCond = LowerSETCC(Cond, DAG);
14525     if (NewCond.getNode())
14526       Cond = NewCond;
14527   }
14528
14529   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14530   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14531   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14532   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14533   if (Cond.getOpcode() == X86ISD::SETCC &&
14534       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14535       isZero(Cond.getOperand(1).getOperand(1))) {
14536     SDValue Cmp = Cond.getOperand(1);
14537
14538     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14539
14540     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14541         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14542       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14543
14544       SDValue CmpOp0 = Cmp.getOperand(0);
14545       // Apply further optimizations for special cases
14546       // (select (x != 0), -1, 0) -> neg & sbb
14547       // (select (x == 0), 0, -1) -> neg & sbb
14548       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14549         if (YC->isNullValue() &&
14550             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14551           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14552           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14553                                     DAG.getConstant(0, DL,
14554                                                     CmpOp0.getValueType()),
14555                                     CmpOp0);
14556           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14557                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14558                                     SDValue(Neg.getNode(), 1));
14559           return Res;
14560         }
14561
14562       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14563                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14564       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14565
14566       SDValue Res =   // Res = 0 or -1.
14567         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14568                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14569
14570       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14571         Res = DAG.getNOT(DL, Res, Res.getValueType());
14572
14573       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14574       if (!N2C || !N2C->isNullValue())
14575         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14576       return Res;
14577     }
14578   }
14579
14580   // Look past (and (setcc_carry (cmp ...)), 1).
14581   if (Cond.getOpcode() == ISD::AND &&
14582       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14583     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14584     if (C && C->getAPIntValue() == 1)
14585       Cond = Cond.getOperand(0);
14586   }
14587
14588   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14589   // setting operand in place of the X86ISD::SETCC.
14590   unsigned CondOpcode = Cond.getOpcode();
14591   if (CondOpcode == X86ISD::SETCC ||
14592       CondOpcode == X86ISD::SETCC_CARRY) {
14593     CC = Cond.getOperand(0);
14594
14595     SDValue Cmp = Cond.getOperand(1);
14596     unsigned Opc = Cmp.getOpcode();
14597     MVT VT = Op.getSimpleValueType();
14598
14599     bool IllegalFPCMov = false;
14600     if (VT.isFloatingPoint() && !VT.isVector() &&
14601         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14602       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14603
14604     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14605         Opc == X86ISD::BT) { // FIXME
14606       Cond = Cmp;
14607       addTest = false;
14608     }
14609   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14610              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14611              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14612               Cond.getOperand(0).getValueType() != MVT::i8)) {
14613     SDValue LHS = Cond.getOperand(0);
14614     SDValue RHS = Cond.getOperand(1);
14615     unsigned X86Opcode;
14616     unsigned X86Cond;
14617     SDVTList VTs;
14618     switch (CondOpcode) {
14619     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14620     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14621     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14622     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14623     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14624     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14625     default: llvm_unreachable("unexpected overflowing operator");
14626     }
14627     if (CondOpcode == ISD::UMULO)
14628       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14629                           MVT::i32);
14630     else
14631       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14632
14633     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14634
14635     if (CondOpcode == ISD::UMULO)
14636       Cond = X86Op.getValue(2);
14637     else
14638       Cond = X86Op.getValue(1);
14639
14640     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14641     addTest = false;
14642   }
14643
14644   if (addTest) {
14645     // Look past the truncate if the high bits are known zero.
14646     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14647       Cond = Cond.getOperand(0);
14648
14649     // We know the result of AND is compared against zero. Try to match
14650     // it to BT.
14651     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14652       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14653       if (NewSetCC.getNode()) {
14654         CC = NewSetCC.getOperand(0);
14655         Cond = NewSetCC.getOperand(1);
14656         addTest = false;
14657       }
14658     }
14659   }
14660
14661   if (addTest) {
14662     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14663     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14664   }
14665
14666   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14667   // a <  b ?  0 : -1 -> RES = setcc_carry
14668   // a >= b ? -1 :  0 -> RES = setcc_carry
14669   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14670   if (Cond.getOpcode() == X86ISD::SUB) {
14671     Cond = ConvertCmpIfNecessary(Cond, DAG);
14672     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14673
14674     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14675         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14676       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14677                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14678                                 Cond);
14679       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14680         return DAG.getNOT(DL, Res, Res.getValueType());
14681       return Res;
14682     }
14683   }
14684
14685   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14686   // widen the cmov and push the truncate through. This avoids introducing a new
14687   // branch during isel and doesn't add any extensions.
14688   if (Op.getValueType() == MVT::i8 &&
14689       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14690     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14691     if (T1.getValueType() == T2.getValueType() &&
14692         // Blacklist CopyFromReg to avoid partial register stalls.
14693         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14694       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14695       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14696       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14697     }
14698   }
14699
14700   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14701   // condition is true.
14702   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14703   SDValue Ops[] = { Op2, Op1, CC, Cond };
14704   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14705 }
14706
14707 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14708                                        const X86Subtarget *Subtarget,
14709                                        SelectionDAG &DAG) {
14710   MVT VT = Op->getSimpleValueType(0);
14711   SDValue In = Op->getOperand(0);
14712   MVT InVT = In.getSimpleValueType();
14713   MVT VTElt = VT.getVectorElementType();
14714   MVT InVTElt = InVT.getVectorElementType();
14715   SDLoc dl(Op);
14716
14717   // SKX processor
14718   if ((InVTElt == MVT::i1) &&
14719       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14720         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14721
14722        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14723         VTElt.getSizeInBits() <= 16)) ||
14724
14725        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14726         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14727
14728        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14729         VTElt.getSizeInBits() >= 32))))
14730     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14731
14732   unsigned int NumElts = VT.getVectorNumElements();
14733
14734   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14735     return SDValue();
14736
14737   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14738     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14739       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14740     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14741   }
14742
14743   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14744   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14745   SDValue NegOne =
14746    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14747                    ExtVT);
14748   SDValue Zero =
14749    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14750
14751   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14752   if (VT.is512BitVector())
14753     return V;
14754   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14755 }
14756
14757 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14758                                              const X86Subtarget *Subtarget,
14759                                              SelectionDAG &DAG) {
14760   SDValue In = Op->getOperand(0);
14761   MVT VT = Op->getSimpleValueType(0);
14762   MVT InVT = In.getSimpleValueType();
14763   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14764
14765   MVT InSVT = InVT.getScalarType();
14766   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14767
14768   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14769     return SDValue();
14770   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14771     return SDValue();
14772
14773   SDLoc dl(Op);
14774
14775   // SSE41 targets can use the pmovsx* instructions directly.
14776   if (Subtarget->hasSSE41())
14777     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14778
14779   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14780   SDValue Curr = In;
14781   MVT CurrVT = InVT;
14782
14783   // As SRAI is only available on i16/i32 types, we expand only up to i32
14784   // and handle i64 separately.
14785   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14786     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14787     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14788     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14789     Curr = DAG.getBitcast(CurrVT, Curr);
14790   }
14791
14792   SDValue SignExt = Curr;
14793   if (CurrVT != InVT) {
14794     unsigned SignExtShift =
14795         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14796     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14797                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14798   }
14799
14800   if (CurrVT == VT)
14801     return SignExt;
14802
14803   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14804     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14805                                DAG.getConstant(31, dl, MVT::i8));
14806     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14807     return DAG.getBitcast(VT, Ext);
14808   }
14809
14810   return SDValue();
14811 }
14812
14813 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14814                                 SelectionDAG &DAG) {
14815   MVT VT = Op->getSimpleValueType(0);
14816   SDValue In = Op->getOperand(0);
14817   MVT InVT = In.getSimpleValueType();
14818   SDLoc dl(Op);
14819
14820   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14821     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14822
14823   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14824       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14825       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14826     return SDValue();
14827
14828   if (Subtarget->hasInt256())
14829     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14830
14831   // Optimize vectors in AVX mode
14832   // Sign extend  v8i16 to v8i32 and
14833   //              v4i32 to v4i64
14834   //
14835   // Divide input vector into two parts
14836   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14837   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14838   // concat the vectors to original VT
14839
14840   unsigned NumElems = InVT.getVectorNumElements();
14841   SDValue Undef = DAG.getUNDEF(InVT);
14842
14843   SmallVector<int,8> ShufMask1(NumElems, -1);
14844   for (unsigned i = 0; i != NumElems/2; ++i)
14845     ShufMask1[i] = i;
14846
14847   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14848
14849   SmallVector<int,8> ShufMask2(NumElems, -1);
14850   for (unsigned i = 0; i != NumElems/2; ++i)
14851     ShufMask2[i] = i + NumElems/2;
14852
14853   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14854
14855   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14856                                 VT.getVectorNumElements()/2);
14857
14858   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14859   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14860
14861   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14862 }
14863
14864 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14865 // may emit an illegal shuffle but the expansion is still better than scalar
14866 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14867 // we'll emit a shuffle and a arithmetic shift.
14868 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14869 // TODO: It is possible to support ZExt by zeroing the undef values during
14870 // the shuffle phase or after the shuffle.
14871 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14872                                  SelectionDAG &DAG) {
14873   MVT RegVT = Op.getSimpleValueType();
14874   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14875   assert(RegVT.isInteger() &&
14876          "We only custom lower integer vector sext loads.");
14877
14878   // Nothing useful we can do without SSE2 shuffles.
14879   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14880
14881   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14882   SDLoc dl(Ld);
14883   EVT MemVT = Ld->getMemoryVT();
14884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14885   unsigned RegSz = RegVT.getSizeInBits();
14886
14887   ISD::LoadExtType Ext = Ld->getExtensionType();
14888
14889   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14890          && "Only anyext and sext are currently implemented.");
14891   assert(MemVT != RegVT && "Cannot extend to the same type");
14892   assert(MemVT.isVector() && "Must load a vector from memory");
14893
14894   unsigned NumElems = RegVT.getVectorNumElements();
14895   unsigned MemSz = MemVT.getSizeInBits();
14896   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14897
14898   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14899     // The only way in which we have a legal 256-bit vector result but not the
14900     // integer 256-bit operations needed to directly lower a sextload is if we
14901     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14902     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14903     // correctly legalized. We do this late to allow the canonical form of
14904     // sextload to persist throughout the rest of the DAG combiner -- it wants
14905     // to fold together any extensions it can, and so will fuse a sign_extend
14906     // of an sextload into a sextload targeting a wider value.
14907     SDValue Load;
14908     if (MemSz == 128) {
14909       // Just switch this to a normal load.
14910       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14911                                        "it must be a legal 128-bit vector "
14912                                        "type!");
14913       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14914                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14915                   Ld->isInvariant(), Ld->getAlignment());
14916     } else {
14917       assert(MemSz < 128 &&
14918              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14919       // Do an sext load to a 128-bit vector type. We want to use the same
14920       // number of elements, but elements half as wide. This will end up being
14921       // recursively lowered by this routine, but will succeed as we definitely
14922       // have all the necessary features if we're using AVX1.
14923       EVT HalfEltVT =
14924           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14925       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14926       Load =
14927           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14928                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14929                          Ld->isNonTemporal(), Ld->isInvariant(),
14930                          Ld->getAlignment());
14931     }
14932
14933     // Replace chain users with the new chain.
14934     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14935     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14936
14937     // Finally, do a normal sign-extend to the desired register.
14938     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14939   }
14940
14941   // All sizes must be a power of two.
14942   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14943          "Non-power-of-two elements are not custom lowered!");
14944
14945   // Attempt to load the original value using scalar loads.
14946   // Find the largest scalar type that divides the total loaded size.
14947   MVT SclrLoadTy = MVT::i8;
14948   for (MVT Tp : MVT::integer_valuetypes()) {
14949     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14950       SclrLoadTy = Tp;
14951     }
14952   }
14953
14954   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14955   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14956       (64 <= MemSz))
14957     SclrLoadTy = MVT::f64;
14958
14959   // Calculate the number of scalar loads that we need to perform
14960   // in order to load our vector from memory.
14961   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14962
14963   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14964          "Can only lower sext loads with a single scalar load!");
14965
14966   unsigned loadRegZize = RegSz;
14967   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14968     loadRegZize = 128;
14969
14970   // Represent our vector as a sequence of elements which are the
14971   // largest scalar that we can load.
14972   EVT LoadUnitVecVT = EVT::getVectorVT(
14973       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14974
14975   // Represent the data using the same element type that is stored in
14976   // memory. In practice, we ''widen'' MemVT.
14977   EVT WideVecVT =
14978       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14979                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14980
14981   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14982          "Invalid vector type");
14983
14984   // We can't shuffle using an illegal type.
14985   assert(TLI.isTypeLegal(WideVecVT) &&
14986          "We only lower types that form legal widened vector types");
14987
14988   SmallVector<SDValue, 8> Chains;
14989   SDValue Ptr = Ld->getBasePtr();
14990   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14991                                       TLI.getPointerTy(DAG.getDataLayout()));
14992   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14993
14994   for (unsigned i = 0; i < NumLoads; ++i) {
14995     // Perform a single load.
14996     SDValue ScalarLoad =
14997         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14998                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14999                     Ld->getAlignment());
15000     Chains.push_back(ScalarLoad.getValue(1));
15001     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15002     // another round of DAGCombining.
15003     if (i == 0)
15004       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15005     else
15006       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15007                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15008
15009     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15010   }
15011
15012   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15013
15014   // Bitcast the loaded value to a vector of the original element type, in
15015   // the size of the target vector type.
15016   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15017   unsigned SizeRatio = RegSz / MemSz;
15018
15019   if (Ext == ISD::SEXTLOAD) {
15020     // If we have SSE4.1, we can directly emit a VSEXT node.
15021     if (Subtarget->hasSSE41()) {
15022       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15023       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15024       return Sext;
15025     }
15026
15027     // Otherwise we'll shuffle the small elements in the high bits of the
15028     // larger type and perform an arithmetic shift. If the shift is not legal
15029     // it's better to scalarize.
15030     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
15031            "We can't implement a sext load without an arithmetic right shift!");
15032
15033     // Redistribute the loaded elements into the different locations.
15034     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15035     for (unsigned i = 0; i != NumElems; ++i)
15036       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
15037
15038     SDValue Shuff = DAG.getVectorShuffle(
15039         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15040
15041     Shuff = DAG.getBitcast(RegVT, Shuff);
15042
15043     // Build the arithmetic shift.
15044     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
15045                    MemVT.getVectorElementType().getSizeInBits();
15046     Shuff =
15047         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
15048                     DAG.getConstant(Amt, dl, RegVT));
15049
15050     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15051     return Shuff;
15052   }
15053
15054   // Redistribute the loaded elements into the different locations.
15055   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15056   for (unsigned i = 0; i != NumElems; ++i)
15057     ShuffleVec[i * SizeRatio] = i;
15058
15059   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15060                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15061
15062   // Bitcast to the requested type.
15063   Shuff = DAG.getBitcast(RegVT, Shuff);
15064   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15065   return Shuff;
15066 }
15067
15068 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15069 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15070 // from the AND / OR.
15071 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15072   Opc = Op.getOpcode();
15073   if (Opc != ISD::OR && Opc != ISD::AND)
15074     return false;
15075   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15076           Op.getOperand(0).hasOneUse() &&
15077           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15078           Op.getOperand(1).hasOneUse());
15079 }
15080
15081 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15082 // 1 and that the SETCC node has a single use.
15083 static bool isXor1OfSetCC(SDValue Op) {
15084   if (Op.getOpcode() != ISD::XOR)
15085     return false;
15086   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15087   if (N1C && N1C->getAPIntValue() == 1) {
15088     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15089       Op.getOperand(0).hasOneUse();
15090   }
15091   return false;
15092 }
15093
15094 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15095   bool addTest = true;
15096   SDValue Chain = Op.getOperand(0);
15097   SDValue Cond  = Op.getOperand(1);
15098   SDValue Dest  = Op.getOperand(2);
15099   SDLoc dl(Op);
15100   SDValue CC;
15101   bool Inverted = false;
15102
15103   if (Cond.getOpcode() == ISD::SETCC) {
15104     // Check for setcc([su]{add,sub,mul}o == 0).
15105     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15106         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15107         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15108         Cond.getOperand(0).getResNo() == 1 &&
15109         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15110          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15111          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15112          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15113          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15114          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15115       Inverted = true;
15116       Cond = Cond.getOperand(0);
15117     } else {
15118       SDValue NewCond = LowerSETCC(Cond, DAG);
15119       if (NewCond.getNode())
15120         Cond = NewCond;
15121     }
15122   }
15123 #if 0
15124   // FIXME: LowerXALUO doesn't handle these!!
15125   else if (Cond.getOpcode() == X86ISD::ADD  ||
15126            Cond.getOpcode() == X86ISD::SUB  ||
15127            Cond.getOpcode() == X86ISD::SMUL ||
15128            Cond.getOpcode() == X86ISD::UMUL)
15129     Cond = LowerXALUO(Cond, DAG);
15130 #endif
15131
15132   // Look pass (and (setcc_carry (cmp ...)), 1).
15133   if (Cond.getOpcode() == ISD::AND &&
15134       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15135     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15136     if (C && C->getAPIntValue() == 1)
15137       Cond = Cond.getOperand(0);
15138   }
15139
15140   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15141   // setting operand in place of the X86ISD::SETCC.
15142   unsigned CondOpcode = Cond.getOpcode();
15143   if (CondOpcode == X86ISD::SETCC ||
15144       CondOpcode == X86ISD::SETCC_CARRY) {
15145     CC = Cond.getOperand(0);
15146
15147     SDValue Cmp = Cond.getOperand(1);
15148     unsigned Opc = Cmp.getOpcode();
15149     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15150     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15151       Cond = Cmp;
15152       addTest = false;
15153     } else {
15154       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15155       default: break;
15156       case X86::COND_O:
15157       case X86::COND_B:
15158         // These can only come from an arithmetic instruction with overflow,
15159         // e.g. SADDO, UADDO.
15160         Cond = Cond.getNode()->getOperand(1);
15161         addTest = false;
15162         break;
15163       }
15164     }
15165   }
15166   CondOpcode = Cond.getOpcode();
15167   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15168       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15169       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15170        Cond.getOperand(0).getValueType() != MVT::i8)) {
15171     SDValue LHS = Cond.getOperand(0);
15172     SDValue RHS = Cond.getOperand(1);
15173     unsigned X86Opcode;
15174     unsigned X86Cond;
15175     SDVTList VTs;
15176     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15177     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15178     // X86ISD::INC).
15179     switch (CondOpcode) {
15180     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15181     case ISD::SADDO:
15182       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15183         if (C->isOne()) {
15184           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15185           break;
15186         }
15187       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15188     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15189     case ISD::SSUBO:
15190       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15191         if (C->isOne()) {
15192           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15193           break;
15194         }
15195       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15196     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15197     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15198     default: llvm_unreachable("unexpected overflowing operator");
15199     }
15200     if (Inverted)
15201       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15202     if (CondOpcode == ISD::UMULO)
15203       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15204                           MVT::i32);
15205     else
15206       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15207
15208     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15209
15210     if (CondOpcode == ISD::UMULO)
15211       Cond = X86Op.getValue(2);
15212     else
15213       Cond = X86Op.getValue(1);
15214
15215     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15216     addTest = false;
15217   } else {
15218     unsigned CondOpc;
15219     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15220       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15221       if (CondOpc == ISD::OR) {
15222         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15223         // two branches instead of an explicit OR instruction with a
15224         // separate test.
15225         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15226             isX86LogicalCmp(Cmp)) {
15227           CC = Cond.getOperand(0).getOperand(0);
15228           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15229                               Chain, Dest, CC, Cmp);
15230           CC = Cond.getOperand(1).getOperand(0);
15231           Cond = Cmp;
15232           addTest = false;
15233         }
15234       } else { // ISD::AND
15235         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15236         // two branches instead of an explicit AND instruction with a
15237         // separate test. However, we only do this if this block doesn't
15238         // have a fall-through edge, because this requires an explicit
15239         // jmp when the condition is false.
15240         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15241             isX86LogicalCmp(Cmp) &&
15242             Op.getNode()->hasOneUse()) {
15243           X86::CondCode CCode =
15244             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15245           CCode = X86::GetOppositeBranchCondition(CCode);
15246           CC = DAG.getConstant(CCode, dl, MVT::i8);
15247           SDNode *User = *Op.getNode()->use_begin();
15248           // Look for an unconditional branch following this conditional branch.
15249           // We need this because we need to reverse the successors in order
15250           // to implement FCMP_OEQ.
15251           if (User->getOpcode() == ISD::BR) {
15252             SDValue FalseBB = User->getOperand(1);
15253             SDNode *NewBR =
15254               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15255             assert(NewBR == User);
15256             (void)NewBR;
15257             Dest = FalseBB;
15258
15259             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15260                                 Chain, Dest, CC, Cmp);
15261             X86::CondCode CCode =
15262               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15263             CCode = X86::GetOppositeBranchCondition(CCode);
15264             CC = DAG.getConstant(CCode, dl, MVT::i8);
15265             Cond = Cmp;
15266             addTest = false;
15267           }
15268         }
15269       }
15270     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15271       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15272       // It should be transformed during dag combiner except when the condition
15273       // is set by a arithmetics with overflow node.
15274       X86::CondCode CCode =
15275         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15276       CCode = X86::GetOppositeBranchCondition(CCode);
15277       CC = DAG.getConstant(CCode, dl, MVT::i8);
15278       Cond = Cond.getOperand(0).getOperand(1);
15279       addTest = false;
15280     } else if (Cond.getOpcode() == ISD::SETCC &&
15281                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15282       // For FCMP_OEQ, we can emit
15283       // two branches instead of an explicit AND instruction with a
15284       // separate test. However, we only do this if this block doesn't
15285       // have a fall-through edge, because this requires an explicit
15286       // jmp when the condition is false.
15287       if (Op.getNode()->hasOneUse()) {
15288         SDNode *User = *Op.getNode()->use_begin();
15289         // Look for an unconditional branch following this conditional branch.
15290         // We need this because we need to reverse the successors in order
15291         // to implement FCMP_OEQ.
15292         if (User->getOpcode() == ISD::BR) {
15293           SDValue FalseBB = User->getOperand(1);
15294           SDNode *NewBR =
15295             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15296           assert(NewBR == User);
15297           (void)NewBR;
15298           Dest = FalseBB;
15299
15300           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15301                                     Cond.getOperand(0), Cond.getOperand(1));
15302           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15303           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15304           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15305                               Chain, Dest, CC, Cmp);
15306           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15307           Cond = Cmp;
15308           addTest = false;
15309         }
15310       }
15311     } else if (Cond.getOpcode() == ISD::SETCC &&
15312                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15313       // For FCMP_UNE, we can emit
15314       // two branches instead of an explicit AND instruction with a
15315       // separate test. However, we only do this if this block doesn't
15316       // have a fall-through edge, because this requires an explicit
15317       // jmp when the condition is false.
15318       if (Op.getNode()->hasOneUse()) {
15319         SDNode *User = *Op.getNode()->use_begin();
15320         // Look for an unconditional branch following this conditional branch.
15321         // We need this because we need to reverse the successors in order
15322         // to implement FCMP_UNE.
15323         if (User->getOpcode() == ISD::BR) {
15324           SDValue FalseBB = User->getOperand(1);
15325           SDNode *NewBR =
15326             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15327           assert(NewBR == User);
15328           (void)NewBR;
15329
15330           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15331                                     Cond.getOperand(0), Cond.getOperand(1));
15332           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15333           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15334           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15335                               Chain, Dest, CC, Cmp);
15336           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15337           Cond = Cmp;
15338           addTest = false;
15339           Dest = FalseBB;
15340         }
15341       }
15342     }
15343   }
15344
15345   if (addTest) {
15346     // Look pass the truncate if the high bits are known zero.
15347     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15348         Cond = Cond.getOperand(0);
15349
15350     // We know the result of AND is compared against zero. Try to match
15351     // it to BT.
15352     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15353       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15354       if (NewSetCC.getNode()) {
15355         CC = NewSetCC.getOperand(0);
15356         Cond = NewSetCC.getOperand(1);
15357         addTest = false;
15358       }
15359     }
15360   }
15361
15362   if (addTest) {
15363     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15364     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15365     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15366   }
15367   Cond = ConvertCmpIfNecessary(Cond, DAG);
15368   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15369                      Chain, Dest, CC, Cond);
15370 }
15371
15372 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15373 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15374 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15375 // that the guard pages used by the OS virtual memory manager are allocated in
15376 // correct sequence.
15377 SDValue
15378 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15379                                            SelectionDAG &DAG) const {
15380   MachineFunction &MF = DAG.getMachineFunction();
15381   bool SplitStack = MF.shouldSplitStack();
15382   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15383                SplitStack;
15384   SDLoc dl(Op);
15385
15386   if (!Lower) {
15387     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15388     SDNode* Node = Op.getNode();
15389
15390     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15391     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15392         " not tell us which reg is the stack pointer!");
15393     EVT VT = Node->getValueType(0);
15394     SDValue Tmp1 = SDValue(Node, 0);
15395     SDValue Tmp2 = SDValue(Node, 1);
15396     SDValue Tmp3 = Node->getOperand(2);
15397     SDValue Chain = Tmp1.getOperand(0);
15398
15399     // Chain the dynamic stack allocation so that it doesn't modify the stack
15400     // pointer when other instructions are using the stack.
15401     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15402         SDLoc(Node));
15403
15404     SDValue Size = Tmp2.getOperand(1);
15405     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15406     Chain = SP.getValue(1);
15407     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15408     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15409     unsigned StackAlign = TFI.getStackAlignment();
15410     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15411     if (Align > StackAlign)
15412       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15413           DAG.getConstant(-(uint64_t)Align, dl, VT));
15414     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15415
15416     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15417         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15418         SDLoc(Node));
15419
15420     SDValue Ops[2] = { Tmp1, Tmp2 };
15421     return DAG.getMergeValues(Ops, dl);
15422   }
15423
15424   // Get the inputs.
15425   SDValue Chain = Op.getOperand(0);
15426   SDValue Size  = Op.getOperand(1);
15427   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15428   EVT VT = Op.getNode()->getValueType(0);
15429
15430   bool Is64Bit = Subtarget->is64Bit();
15431   MVT SPTy = getPointerTy(DAG.getDataLayout());
15432
15433   if (SplitStack) {
15434     MachineRegisterInfo &MRI = MF.getRegInfo();
15435
15436     if (Is64Bit) {
15437       // The 64 bit implementation of segmented stacks needs to clobber both r10
15438       // r11. This makes it impossible to use it along with nested parameters.
15439       const Function *F = MF.getFunction();
15440
15441       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15442            I != E; ++I)
15443         if (I->hasNestAttr())
15444           report_fatal_error("Cannot use segmented stacks with functions that "
15445                              "have nested arguments.");
15446     }
15447
15448     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15449     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15450     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15451     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15452                                 DAG.getRegister(Vreg, SPTy));
15453     SDValue Ops1[2] = { Value, Chain };
15454     return DAG.getMergeValues(Ops1, dl);
15455   } else {
15456     SDValue Flag;
15457     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15458
15459     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15460     Flag = Chain.getValue(1);
15461     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15462
15463     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15464
15465     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15466     unsigned SPReg = RegInfo->getStackRegister();
15467     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15468     Chain = SP.getValue(1);
15469
15470     if (Align) {
15471       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15472                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15473       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15474     }
15475
15476     SDValue Ops1[2] = { SP, Chain };
15477     return DAG.getMergeValues(Ops1, dl);
15478   }
15479 }
15480
15481 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15482   MachineFunction &MF = DAG.getMachineFunction();
15483   auto PtrVT = getPointerTy(MF.getDataLayout());
15484   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15485
15486   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15487   SDLoc DL(Op);
15488
15489   if (!Subtarget->is64Bit() ||
15490       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15491     // vastart just stores the address of the VarArgsFrameIndex slot into the
15492     // memory location argument.
15493     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15494     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15495                         MachinePointerInfo(SV), false, false, 0);
15496   }
15497
15498   // __va_list_tag:
15499   //   gp_offset         (0 - 6 * 8)
15500   //   fp_offset         (48 - 48 + 8 * 16)
15501   //   overflow_arg_area (point to parameters coming in memory).
15502   //   reg_save_area
15503   SmallVector<SDValue, 8> MemOps;
15504   SDValue FIN = Op.getOperand(1);
15505   // Store gp_offset
15506   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15507                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15508                                                DL, MVT::i32),
15509                                FIN, MachinePointerInfo(SV), false, false, 0);
15510   MemOps.push_back(Store);
15511
15512   // Store fp_offset
15513   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15514   Store = DAG.getStore(Op.getOperand(0), DL,
15515                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15516                                        MVT::i32),
15517                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15518   MemOps.push_back(Store);
15519
15520   // Store ptr to overflow_arg_area
15521   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15522   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15523   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15524                        MachinePointerInfo(SV, 8),
15525                        false, false, 0);
15526   MemOps.push_back(Store);
15527
15528   // Store ptr to reg_save_area.
15529   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15530       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15531   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15532   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15533       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15534   MemOps.push_back(Store);
15535   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15536 }
15537
15538 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15539   assert(Subtarget->is64Bit() &&
15540          "LowerVAARG only handles 64-bit va_arg!");
15541   assert(Op.getNode()->getNumOperands() == 4);
15542
15543   MachineFunction &MF = DAG.getMachineFunction();
15544   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15545     // The Win64 ABI uses char* instead of a structure.
15546     return DAG.expandVAArg(Op.getNode());
15547
15548   SDValue Chain = Op.getOperand(0);
15549   SDValue SrcPtr = Op.getOperand(1);
15550   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15551   unsigned Align = Op.getConstantOperandVal(3);
15552   SDLoc dl(Op);
15553
15554   EVT ArgVT = Op.getNode()->getValueType(0);
15555   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15556   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15557   uint8_t ArgMode;
15558
15559   // Decide which area this value should be read from.
15560   // TODO: Implement the AMD64 ABI in its entirety. This simple
15561   // selection mechanism works only for the basic types.
15562   if (ArgVT == MVT::f80) {
15563     llvm_unreachable("va_arg for f80 not yet implemented");
15564   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15565     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15566   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15567     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15568   } else {
15569     llvm_unreachable("Unhandled argument type in LowerVAARG");
15570   }
15571
15572   if (ArgMode == 2) {
15573     // Sanity Check: Make sure using fp_offset makes sense.
15574     assert(!Subtarget->useSoftFloat() &&
15575            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15576            Subtarget->hasSSE1());
15577   }
15578
15579   // Insert VAARG_64 node into the DAG
15580   // VAARG_64 returns two values: Variable Argument Address, Chain
15581   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15582                        DAG.getConstant(ArgMode, dl, MVT::i8),
15583                        DAG.getConstant(Align, dl, MVT::i32)};
15584   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15585   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15586                                           VTs, InstOps, MVT::i64,
15587                                           MachinePointerInfo(SV),
15588                                           /*Align=*/0,
15589                                           /*Volatile=*/false,
15590                                           /*ReadMem=*/true,
15591                                           /*WriteMem=*/true);
15592   Chain = VAARG.getValue(1);
15593
15594   // Load the next argument and return it
15595   return DAG.getLoad(ArgVT, dl,
15596                      Chain,
15597                      VAARG,
15598                      MachinePointerInfo(),
15599                      false, false, false, 0);
15600 }
15601
15602 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15603                            SelectionDAG &DAG) {
15604   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15605   // where a va_list is still an i8*.
15606   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15607   if (Subtarget->isCallingConvWin64(
15608         DAG.getMachineFunction().getFunction()->getCallingConv()))
15609     // Probably a Win64 va_copy.
15610     return DAG.expandVACopy(Op.getNode());
15611
15612   SDValue Chain = Op.getOperand(0);
15613   SDValue DstPtr = Op.getOperand(1);
15614   SDValue SrcPtr = Op.getOperand(2);
15615   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15616   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15617   SDLoc DL(Op);
15618
15619   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15620                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15621                        false, false,
15622                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15623 }
15624
15625 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15626 // amount is a constant. Takes immediate version of shift as input.
15627 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15628                                           SDValue SrcOp, uint64_t ShiftAmt,
15629                                           SelectionDAG &DAG) {
15630   MVT ElementType = VT.getVectorElementType();
15631
15632   // Fold this packed shift into its first operand if ShiftAmt is 0.
15633   if (ShiftAmt == 0)
15634     return SrcOp;
15635
15636   // Check for ShiftAmt >= element width
15637   if (ShiftAmt >= ElementType.getSizeInBits()) {
15638     if (Opc == X86ISD::VSRAI)
15639       ShiftAmt = ElementType.getSizeInBits() - 1;
15640     else
15641       return DAG.getConstant(0, dl, VT);
15642   }
15643
15644   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15645          && "Unknown target vector shift-by-constant node");
15646
15647   // Fold this packed vector shift into a build vector if SrcOp is a
15648   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15649   if (VT == SrcOp.getSimpleValueType() &&
15650       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15651     SmallVector<SDValue, 8> Elts;
15652     unsigned NumElts = SrcOp->getNumOperands();
15653     ConstantSDNode *ND;
15654
15655     switch(Opc) {
15656     default: llvm_unreachable(nullptr);
15657     case X86ISD::VSHLI:
15658       for (unsigned i=0; i!=NumElts; ++i) {
15659         SDValue CurrentOp = SrcOp->getOperand(i);
15660         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15661           Elts.push_back(CurrentOp);
15662           continue;
15663         }
15664         ND = cast<ConstantSDNode>(CurrentOp);
15665         const APInt &C = ND->getAPIntValue();
15666         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15667       }
15668       break;
15669     case X86ISD::VSRLI:
15670       for (unsigned i=0; i!=NumElts; ++i) {
15671         SDValue CurrentOp = SrcOp->getOperand(i);
15672         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15673           Elts.push_back(CurrentOp);
15674           continue;
15675         }
15676         ND = cast<ConstantSDNode>(CurrentOp);
15677         const APInt &C = ND->getAPIntValue();
15678         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15679       }
15680       break;
15681     case X86ISD::VSRAI:
15682       for (unsigned i=0; i!=NumElts; ++i) {
15683         SDValue CurrentOp = SrcOp->getOperand(i);
15684         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15685           Elts.push_back(CurrentOp);
15686           continue;
15687         }
15688         ND = cast<ConstantSDNode>(CurrentOp);
15689         const APInt &C = ND->getAPIntValue();
15690         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15691       }
15692       break;
15693     }
15694
15695     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15696   }
15697
15698   return DAG.getNode(Opc, dl, VT, SrcOp,
15699                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15700 }
15701
15702 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15703 // may or may not be a constant. Takes immediate version of shift as input.
15704 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15705                                    SDValue SrcOp, SDValue ShAmt,
15706                                    SelectionDAG &DAG) {
15707   MVT SVT = ShAmt.getSimpleValueType();
15708   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15709
15710   // Catch shift-by-constant.
15711   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15712     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15713                                       CShAmt->getZExtValue(), DAG);
15714
15715   // Change opcode to non-immediate version
15716   switch (Opc) {
15717     default: llvm_unreachable("Unknown target vector shift node");
15718     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15719     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15720     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15721   }
15722
15723   const X86Subtarget &Subtarget =
15724       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15725   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15726       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15727     // Let the shuffle legalizer expand this shift amount node.
15728     SDValue Op0 = ShAmt.getOperand(0);
15729     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15730     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15731   } else {
15732     // Need to build a vector containing shift amount.
15733     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15734     SmallVector<SDValue, 4> ShOps;
15735     ShOps.push_back(ShAmt);
15736     if (SVT == MVT::i32) {
15737       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15738       ShOps.push_back(DAG.getUNDEF(SVT));
15739     }
15740     ShOps.push_back(DAG.getUNDEF(SVT));
15741
15742     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15743     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15744   }
15745
15746   // The return type has to be a 128-bit type with the same element
15747   // type as the input type.
15748   MVT EltVT = VT.getVectorElementType();
15749   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15750
15751   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15752   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15753 }
15754
15755 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15756 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15757 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15758 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15759                                     SDValue PreservedSrc,
15760                                     const X86Subtarget *Subtarget,
15761                                     SelectionDAG &DAG) {
15762     EVT VT = Op.getValueType();
15763     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15764                                   MVT::i1, VT.getVectorNumElements());
15765     SDValue VMask = SDValue();
15766     unsigned OpcodeSelect = ISD::VSELECT;
15767     SDLoc dl(Op);
15768
15769     assert(MaskVT.isSimple() && "invalid mask type");
15770
15771     if (isAllOnes(Mask))
15772       return Op;
15773
15774     if (MaskVT.bitsGT(Mask.getValueType())) {
15775       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15776                                          MaskVT.getSizeInBits());
15777       VMask = DAG.getBitcast(MaskVT,
15778                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15779     } else {
15780       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15781                                        Mask.getValueType().getSizeInBits());
15782       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15783       // are extracted by EXTRACT_SUBVECTOR.
15784       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15785                           DAG.getBitcast(BitcastVT, Mask),
15786                           DAG.getIntPtrConstant(0, dl));
15787     }
15788
15789     switch (Op.getOpcode()) {
15790       default: break;
15791       case X86ISD::PCMPEQM:
15792       case X86ISD::PCMPGTM:
15793       case X86ISD::CMPM:
15794       case X86ISD::CMPMU:
15795         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15796       case X86ISD::VFPCLASS:
15797         return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15798       case X86ISD::VTRUNC:
15799       case X86ISD::VTRUNCS:
15800       case X86ISD::VTRUNCUS:
15801         // We can't use ISD::VSELECT here because it is not always "Legal"
15802         // for the destination type. For example vpmovqb require only AVX512
15803         // and vselect that can operate on byte element type require BWI
15804         OpcodeSelect = X86ISD::SELECT;
15805         break;
15806     }
15807     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15808       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15809     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15810 }
15811
15812 /// \brief Creates an SDNode for a predicated scalar operation.
15813 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15814 /// The mask is coming as MVT::i8 and it should be truncated
15815 /// to MVT::i1 while lowering masking intrinsics.
15816 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15817 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15818 /// for a scalar instruction.
15819 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15820                                     SDValue PreservedSrc,
15821                                     const X86Subtarget *Subtarget,
15822                                     SelectionDAG &DAG) {
15823   if (isAllOnes(Mask))
15824     return Op;
15825
15826   EVT VT = Op.getValueType();
15827   SDLoc dl(Op);
15828   // The mask should be of type MVT::i1
15829   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15830
15831   if (Op.getOpcode() == X86ISD::FSETCC)
15832     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15833
15834   if (PreservedSrc.getOpcode() == ISD::UNDEF)
15835     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15836   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15837 }
15838
15839 static int getSEHRegistrationNodeSize(const Function *Fn) {
15840   if (!Fn->hasPersonalityFn())
15841     report_fatal_error(
15842         "querying registration node size for function without personality");
15843   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15844   // WinEHStatePass for the full struct definition.
15845   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15846   case EHPersonality::MSVC_X86SEH: return 24;
15847   case EHPersonality::MSVC_CXX: return 16;
15848   default: break;
15849   }
15850   report_fatal_error("can only recover FP for MSVC EH personality functions");
15851 }
15852
15853 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15854 /// function or when returning to a parent frame after catching an exception, we
15855 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15856 /// Here's the math:
15857 ///   RegNodeBase = EntryEBP - RegNodeSize
15858 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15859 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15860 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15861 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15862                                    SDValue EntryEBP) {
15863   MachineFunction &MF = DAG.getMachineFunction();
15864   SDLoc dl;
15865
15866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15867   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15868
15869   // It's possible that the parent function no longer has a personality function
15870   // if the exceptional code was optimized away, in which case we just return
15871   // the incoming EBP.
15872   if (!Fn->hasPersonalityFn())
15873     return EntryEBP;
15874
15875   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15876
15877   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15878   // registration.
15879   MCSymbol *OffsetSym =
15880       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15881           GlobalValue::getRealLinkageName(Fn->getName()));
15882   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15883   SDValue RegNodeFrameOffset =
15884       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15885
15886   // RegNodeBase = EntryEBP - RegNodeSize
15887   // ParentFP = RegNodeBase - RegNodeFrameOffset
15888   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15889                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15890   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15891 }
15892
15893 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15894                                        SelectionDAG &DAG) {
15895   SDLoc dl(Op);
15896   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15897   EVT VT = Op.getValueType();
15898   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15899   if (IntrData) {
15900     switch(IntrData->Type) {
15901     case INTR_TYPE_1OP:
15902       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15903     case INTR_TYPE_2OP:
15904       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15905         Op.getOperand(2));
15906     case INTR_TYPE_2OP_IMM8:
15907       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15908                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15909     case INTR_TYPE_3OP:
15910       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15911         Op.getOperand(2), Op.getOperand(3));
15912     case INTR_TYPE_4OP:
15913       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15914         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15915     case INTR_TYPE_1OP_MASK_RM: {
15916       SDValue Src = Op.getOperand(1);
15917       SDValue PassThru = Op.getOperand(2);
15918       SDValue Mask = Op.getOperand(3);
15919       SDValue RoundingMode;
15920       // We allways add rounding mode to the Node.
15921       // If the rounding mode is not specified, we add the
15922       // "current direction" mode.
15923       if (Op.getNumOperands() == 4)
15924         RoundingMode =
15925           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15926       else
15927         RoundingMode = Op.getOperand(4);
15928       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15929       if (IntrWithRoundingModeOpcode != 0)
15930         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15931             X86::STATIC_ROUNDING::CUR_DIRECTION)
15932           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15933                                       dl, Op.getValueType(), Src, RoundingMode),
15934                                       Mask, PassThru, Subtarget, DAG);
15935       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15936                                               RoundingMode),
15937                                   Mask, PassThru, Subtarget, DAG);
15938     }
15939     case INTR_TYPE_1OP_MASK: {
15940       SDValue Src = Op.getOperand(1);
15941       SDValue PassThru = Op.getOperand(2);
15942       SDValue Mask = Op.getOperand(3);
15943       // We add rounding mode to the Node when
15944       //   - RM Opcode is specified and
15945       //   - RM is not "current direction".
15946       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15947       if (IntrWithRoundingModeOpcode != 0) {
15948         SDValue Rnd = Op.getOperand(4);
15949         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15950         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15951           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15952                                       dl, Op.getValueType(),
15953                                       Src, Rnd),
15954                                       Mask, PassThru, Subtarget, DAG);
15955         }
15956       }
15957       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15958                                   Mask, PassThru, Subtarget, DAG);
15959     }
15960     case INTR_TYPE_SCALAR_MASK: {
15961       SDValue Src1 = Op.getOperand(1);
15962       SDValue Src2 = Op.getOperand(2);
15963       SDValue passThru = Op.getOperand(3);
15964       SDValue Mask = Op.getOperand(4);
15965       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
15966                                   Mask, passThru, Subtarget, DAG);
15967     }
15968     case INTR_TYPE_SCALAR_MASK_RM: {
15969       SDValue Src1 = Op.getOperand(1);
15970       SDValue Src2 = Op.getOperand(2);
15971       SDValue Src0 = Op.getOperand(3);
15972       SDValue Mask = Op.getOperand(4);
15973       // There are 2 kinds of intrinsics in this group:
15974       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15975       // (2) With rounding mode and sae - 7 operands.
15976       if (Op.getNumOperands() == 6) {
15977         SDValue Sae  = Op.getOperand(5);
15978         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15979         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15980                                                 Sae),
15981                                     Mask, Src0, Subtarget, DAG);
15982       }
15983       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15984       SDValue RoundingMode  = Op.getOperand(5);
15985       SDValue Sae  = Op.getOperand(6);
15986       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15987                                               RoundingMode, Sae),
15988                                   Mask, Src0, Subtarget, DAG);
15989     }
15990     case INTR_TYPE_2OP_MASK: {
15991       SDValue Src1 = Op.getOperand(1);
15992       SDValue Src2 = Op.getOperand(2);
15993       SDValue PassThru = Op.getOperand(3);
15994       SDValue Mask = Op.getOperand(4);
15995       // We specify 2 possible opcodes for intrinsics with rounding modes.
15996       // First, we check if the intrinsic may have non-default rounding mode,
15997       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15998       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15999       if (IntrWithRoundingModeOpcode != 0) {
16000         SDValue Rnd = Op.getOperand(5);
16001         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16002         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16003           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16004                                       dl, Op.getValueType(),
16005                                       Src1, Src2, Rnd),
16006                                       Mask, PassThru, Subtarget, DAG);
16007         }
16008       }
16009       // TODO: Intrinsics should have fast-math-flags to propagate.
16010       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16011                                   Mask, PassThru, Subtarget, DAG);
16012     }
16013     case INTR_TYPE_2OP_MASK_RM: {
16014       SDValue Src1 = Op.getOperand(1);
16015       SDValue Src2 = Op.getOperand(2);
16016       SDValue PassThru = Op.getOperand(3);
16017       SDValue Mask = Op.getOperand(4);
16018       // We specify 2 possible modes for intrinsics, with/without rounding
16019       // modes.
16020       // First, we check if the intrinsic have rounding mode (6 operands),
16021       // if not, we set rounding mode to "current".
16022       SDValue Rnd;
16023       if (Op.getNumOperands() == 6)
16024         Rnd = Op.getOperand(5);
16025       else
16026         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16027       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16028                                               Src1, Src2, Rnd),
16029                                   Mask, PassThru, Subtarget, DAG);
16030     }
16031     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16032       SDValue Src1 = Op.getOperand(1);
16033       SDValue Src2 = Op.getOperand(2);
16034       SDValue Src3 = Op.getOperand(3);
16035       SDValue PassThru = Op.getOperand(4);
16036       SDValue Mask = Op.getOperand(5);
16037       SDValue Sae  = Op.getOperand(6);
16038
16039       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16040                                               Src2, Src3, Sae),
16041                                   Mask, PassThru, Subtarget, DAG);
16042     }
16043     case INTR_TYPE_3OP_MASK_RM: {
16044       SDValue Src1 = Op.getOperand(1);
16045       SDValue Src2 = Op.getOperand(2);
16046       SDValue Imm = Op.getOperand(3);
16047       SDValue PassThru = Op.getOperand(4);
16048       SDValue Mask = Op.getOperand(5);
16049       // We specify 2 possible modes for intrinsics, with/without rounding
16050       // modes.
16051       // First, we check if the intrinsic have rounding mode (7 operands),
16052       // if not, we set rounding mode to "current".
16053       SDValue Rnd;
16054       if (Op.getNumOperands() == 7)
16055         Rnd = Op.getOperand(6);
16056       else
16057         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16058       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16059         Src1, Src2, Imm, Rnd),
16060         Mask, PassThru, Subtarget, DAG);
16061     }
16062     case INTR_TYPE_3OP_IMM8_MASK:
16063     case INTR_TYPE_3OP_MASK:
16064     case INSERT_SUBVEC: {
16065       SDValue Src1 = Op.getOperand(1);
16066       SDValue Src2 = Op.getOperand(2);
16067       SDValue Src3 = Op.getOperand(3);
16068       SDValue PassThru = Op.getOperand(4);
16069       SDValue Mask = Op.getOperand(5);
16070
16071       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16072         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16073       else if (IntrData->Type == INSERT_SUBVEC) {
16074         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16075         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16076         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16077         Imm *= Src2.getValueType().getVectorNumElements();
16078         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16079       }
16080
16081       // We specify 2 possible opcodes for intrinsics with rounding modes.
16082       // First, we check if the intrinsic may have non-default rounding mode,
16083       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16084       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16085       if (IntrWithRoundingModeOpcode != 0) {
16086         SDValue Rnd = Op.getOperand(6);
16087         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16088         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16089           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16090                                       dl, Op.getValueType(),
16091                                       Src1, Src2, Src3, Rnd),
16092                                       Mask, PassThru, Subtarget, DAG);
16093         }
16094       }
16095       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16096                                               Src1, Src2, Src3),
16097                                   Mask, PassThru, Subtarget, DAG);
16098     }
16099     case VPERM_3OP_MASKZ:
16100     case VPERM_3OP_MASK:
16101     case FMA_OP_MASK3:
16102     case FMA_OP_MASKZ:
16103     case FMA_OP_MASK: {
16104       SDValue Src1 = Op.getOperand(1);
16105       SDValue Src2 = Op.getOperand(2);
16106       SDValue Src3 = Op.getOperand(3);
16107       SDValue Mask = Op.getOperand(4);
16108       EVT VT = Op.getValueType();
16109       SDValue PassThru = SDValue();
16110
16111       // set PassThru element
16112       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16113         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16114       else if (IntrData->Type == FMA_OP_MASK3)
16115         PassThru = Src3;
16116       else
16117         PassThru = Src1;
16118
16119       // We specify 2 possible opcodes for intrinsics with rounding modes.
16120       // First, we check if the intrinsic may have non-default rounding mode,
16121       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16122       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16123       if (IntrWithRoundingModeOpcode != 0) {
16124         SDValue Rnd = Op.getOperand(5);
16125         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16126             X86::STATIC_ROUNDING::CUR_DIRECTION)
16127           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16128                                                   dl, Op.getValueType(),
16129                                                   Src1, Src2, Src3, Rnd),
16130                                       Mask, PassThru, Subtarget, DAG);
16131       }
16132       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16133                                               dl, Op.getValueType(),
16134                                               Src1, Src2, Src3),
16135                                   Mask, PassThru, Subtarget, DAG);
16136     }
16137     case FPCLASS: {
16138       // FPclass intrinsics with mask
16139        SDValue Src1 = Op.getOperand(1);
16140        EVT VT = Src1.getValueType();
16141        EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16142                                       VT.getVectorNumElements());
16143        SDValue Imm = Op.getOperand(2);
16144        SDValue Mask = Op.getOperand(3);
16145        EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16146                                         Mask.getValueType().getSizeInBits());
16147        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16148        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16149                                                  DAG.getTargetConstant(0, dl, MaskVT),
16150                                                  Subtarget, DAG);
16151        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16152                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16153                                  DAG.getIntPtrConstant(0, dl));
16154        return DAG.getBitcast(Op.getValueType(), Res);
16155     }
16156     case CMP_MASK:
16157     case CMP_MASK_CC: {
16158       // Comparison intrinsics with masks.
16159       // Example of transformation:
16160       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16161       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16162       // (i8 (bitcast
16163       //   (v8i1 (insert_subvector undef,
16164       //           (v2i1 (and (PCMPEQM %a, %b),
16165       //                      (extract_subvector
16166       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16167       EVT VT = Op.getOperand(1).getValueType();
16168       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16169                                     VT.getVectorNumElements());
16170       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16171       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16172                                        Mask.getValueType().getSizeInBits());
16173       SDValue Cmp;
16174       if (IntrData->Type == CMP_MASK_CC) {
16175         SDValue CC = Op.getOperand(3);
16176         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16177         // We specify 2 possible opcodes for intrinsics with rounding modes.
16178         // First, we check if the intrinsic may have non-default rounding mode,
16179         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16180         if (IntrData->Opc1 != 0) {
16181           SDValue Rnd = Op.getOperand(5);
16182           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16183               X86::STATIC_ROUNDING::CUR_DIRECTION)
16184             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16185                               Op.getOperand(2), CC, Rnd);
16186         }
16187         //default rounding mode
16188         if(!Cmp.getNode())
16189             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16190                               Op.getOperand(2), CC);
16191
16192       } else {
16193         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16194         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16195                           Op.getOperand(2));
16196       }
16197       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16198                                              DAG.getTargetConstant(0, dl,
16199                                                                    MaskVT),
16200                                              Subtarget, DAG);
16201       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16202                                 DAG.getUNDEF(BitcastVT), CmpMask,
16203                                 DAG.getIntPtrConstant(0, dl));
16204       return DAG.getBitcast(Op.getValueType(), Res);
16205     }
16206     case CMP_MASK_SCALAR_CC: {
16207       SDValue Src1 = Op.getOperand(1);
16208       SDValue Src2 = Op.getOperand(2);
16209       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16210       SDValue Mask = Op.getOperand(4);
16211
16212       SDValue Cmp;
16213       if (IntrData->Opc1 != 0) {
16214         SDValue Rnd = Op.getOperand(5);
16215         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16216             X86::STATIC_ROUNDING::CUR_DIRECTION)
16217           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16218       }
16219       //default rounding mode
16220       if(!Cmp.getNode())
16221         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16222
16223       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16224                                              DAG.getTargetConstant(0, dl,
16225                                                                    MVT::i1),
16226                                              Subtarget, DAG);
16227
16228       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16229                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16230                          DAG.getValueType(MVT::i1));
16231     }
16232     case COMI: { // Comparison intrinsics
16233       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16234       SDValue LHS = Op.getOperand(1);
16235       SDValue RHS = Op.getOperand(2);
16236       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16237       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16238       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16239       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16240                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16241       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16242     }
16243     case VSHIFT:
16244       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16245                                  Op.getOperand(1), Op.getOperand(2), DAG);
16246     case VSHIFT_MASK:
16247       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16248                                                       Op.getSimpleValueType(),
16249                                                       Op.getOperand(1),
16250                                                       Op.getOperand(2), DAG),
16251                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16252                                   DAG);
16253     case COMPRESS_EXPAND_IN_REG: {
16254       SDValue Mask = Op.getOperand(3);
16255       SDValue DataToCompress = Op.getOperand(1);
16256       SDValue PassThru = Op.getOperand(2);
16257       if (isAllOnes(Mask)) // return data as is
16258         return Op.getOperand(1);
16259
16260       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16261                                               DataToCompress),
16262                                   Mask, PassThru, Subtarget, DAG);
16263     }
16264     case BLEND: {
16265       SDValue Mask = Op.getOperand(3);
16266       EVT VT = Op.getValueType();
16267       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16268                                     VT.getVectorNumElements());
16269       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16270                                        Mask.getValueType().getSizeInBits());
16271       SDLoc dl(Op);
16272       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16273                                   DAG.getBitcast(BitcastVT, Mask),
16274                                   DAG.getIntPtrConstant(0, dl));
16275       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16276                          Op.getOperand(2));
16277     }
16278     default:
16279       break;
16280     }
16281   }
16282
16283   switch (IntNo) {
16284   default: return SDValue();    // Don't custom lower most intrinsics.
16285
16286   case Intrinsic::x86_avx2_permd:
16287   case Intrinsic::x86_avx2_permps:
16288     // Operands intentionally swapped. Mask is last operand to intrinsic,
16289     // but second operand for node/instruction.
16290     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16291                        Op.getOperand(2), Op.getOperand(1));
16292
16293   // ptest and testp intrinsics. The intrinsic these come from are designed to
16294   // return an integer value, not just an instruction so lower it to the ptest
16295   // or testp pattern and a setcc for the result.
16296   case Intrinsic::x86_sse41_ptestz:
16297   case Intrinsic::x86_sse41_ptestc:
16298   case Intrinsic::x86_sse41_ptestnzc:
16299   case Intrinsic::x86_avx_ptestz_256:
16300   case Intrinsic::x86_avx_ptestc_256:
16301   case Intrinsic::x86_avx_ptestnzc_256:
16302   case Intrinsic::x86_avx_vtestz_ps:
16303   case Intrinsic::x86_avx_vtestc_ps:
16304   case Intrinsic::x86_avx_vtestnzc_ps:
16305   case Intrinsic::x86_avx_vtestz_pd:
16306   case Intrinsic::x86_avx_vtestc_pd:
16307   case Intrinsic::x86_avx_vtestnzc_pd:
16308   case Intrinsic::x86_avx_vtestz_ps_256:
16309   case Intrinsic::x86_avx_vtestc_ps_256:
16310   case Intrinsic::x86_avx_vtestnzc_ps_256:
16311   case Intrinsic::x86_avx_vtestz_pd_256:
16312   case Intrinsic::x86_avx_vtestc_pd_256:
16313   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16314     bool IsTestPacked = false;
16315     unsigned X86CC;
16316     switch (IntNo) {
16317     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16318     case Intrinsic::x86_avx_vtestz_ps:
16319     case Intrinsic::x86_avx_vtestz_pd:
16320     case Intrinsic::x86_avx_vtestz_ps_256:
16321     case Intrinsic::x86_avx_vtestz_pd_256:
16322       IsTestPacked = true; // Fallthrough
16323     case Intrinsic::x86_sse41_ptestz:
16324     case Intrinsic::x86_avx_ptestz_256:
16325       // ZF = 1
16326       X86CC = X86::COND_E;
16327       break;
16328     case Intrinsic::x86_avx_vtestc_ps:
16329     case Intrinsic::x86_avx_vtestc_pd:
16330     case Intrinsic::x86_avx_vtestc_ps_256:
16331     case Intrinsic::x86_avx_vtestc_pd_256:
16332       IsTestPacked = true; // Fallthrough
16333     case Intrinsic::x86_sse41_ptestc:
16334     case Intrinsic::x86_avx_ptestc_256:
16335       // CF = 1
16336       X86CC = X86::COND_B;
16337       break;
16338     case Intrinsic::x86_avx_vtestnzc_ps:
16339     case Intrinsic::x86_avx_vtestnzc_pd:
16340     case Intrinsic::x86_avx_vtestnzc_ps_256:
16341     case Intrinsic::x86_avx_vtestnzc_pd_256:
16342       IsTestPacked = true; // Fallthrough
16343     case Intrinsic::x86_sse41_ptestnzc:
16344     case Intrinsic::x86_avx_ptestnzc_256:
16345       // ZF and CF = 0
16346       X86CC = X86::COND_A;
16347       break;
16348     }
16349
16350     SDValue LHS = Op.getOperand(1);
16351     SDValue RHS = Op.getOperand(2);
16352     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16353     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16354     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16355     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16356     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16357   }
16358   case Intrinsic::x86_avx512_kortestz_w:
16359   case Intrinsic::x86_avx512_kortestc_w: {
16360     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16361     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16362     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16363     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16364     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16365     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16366     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16367   }
16368
16369   case Intrinsic::x86_sse42_pcmpistria128:
16370   case Intrinsic::x86_sse42_pcmpestria128:
16371   case Intrinsic::x86_sse42_pcmpistric128:
16372   case Intrinsic::x86_sse42_pcmpestric128:
16373   case Intrinsic::x86_sse42_pcmpistrio128:
16374   case Intrinsic::x86_sse42_pcmpestrio128:
16375   case Intrinsic::x86_sse42_pcmpistris128:
16376   case Intrinsic::x86_sse42_pcmpestris128:
16377   case Intrinsic::x86_sse42_pcmpistriz128:
16378   case Intrinsic::x86_sse42_pcmpestriz128: {
16379     unsigned Opcode;
16380     unsigned X86CC;
16381     switch (IntNo) {
16382     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16383     case Intrinsic::x86_sse42_pcmpistria128:
16384       Opcode = X86ISD::PCMPISTRI;
16385       X86CC = X86::COND_A;
16386       break;
16387     case Intrinsic::x86_sse42_pcmpestria128:
16388       Opcode = X86ISD::PCMPESTRI;
16389       X86CC = X86::COND_A;
16390       break;
16391     case Intrinsic::x86_sse42_pcmpistric128:
16392       Opcode = X86ISD::PCMPISTRI;
16393       X86CC = X86::COND_B;
16394       break;
16395     case Intrinsic::x86_sse42_pcmpestric128:
16396       Opcode = X86ISD::PCMPESTRI;
16397       X86CC = X86::COND_B;
16398       break;
16399     case Intrinsic::x86_sse42_pcmpistrio128:
16400       Opcode = X86ISD::PCMPISTRI;
16401       X86CC = X86::COND_O;
16402       break;
16403     case Intrinsic::x86_sse42_pcmpestrio128:
16404       Opcode = X86ISD::PCMPESTRI;
16405       X86CC = X86::COND_O;
16406       break;
16407     case Intrinsic::x86_sse42_pcmpistris128:
16408       Opcode = X86ISD::PCMPISTRI;
16409       X86CC = X86::COND_S;
16410       break;
16411     case Intrinsic::x86_sse42_pcmpestris128:
16412       Opcode = X86ISD::PCMPESTRI;
16413       X86CC = X86::COND_S;
16414       break;
16415     case Intrinsic::x86_sse42_pcmpistriz128:
16416       Opcode = X86ISD::PCMPISTRI;
16417       X86CC = X86::COND_E;
16418       break;
16419     case Intrinsic::x86_sse42_pcmpestriz128:
16420       Opcode = X86ISD::PCMPESTRI;
16421       X86CC = X86::COND_E;
16422       break;
16423     }
16424     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16425     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16426     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16427     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16428                                 DAG.getConstant(X86CC, dl, MVT::i8),
16429                                 SDValue(PCMP.getNode(), 1));
16430     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16431   }
16432
16433   case Intrinsic::x86_sse42_pcmpistri128:
16434   case Intrinsic::x86_sse42_pcmpestri128: {
16435     unsigned Opcode;
16436     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16437       Opcode = X86ISD::PCMPISTRI;
16438     else
16439       Opcode = X86ISD::PCMPESTRI;
16440
16441     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16442     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16443     return DAG.getNode(Opcode, dl, VTs, NewOps);
16444   }
16445
16446   case Intrinsic::x86_seh_lsda: {
16447     // Compute the symbol for the LSDA. We know it'll get emitted later.
16448     MachineFunction &MF = DAG.getMachineFunction();
16449     SDValue Op1 = Op.getOperand(1);
16450     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16451     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16452         GlobalValue::getRealLinkageName(Fn->getName()));
16453
16454     // Generate a simple absolute symbol reference. This intrinsic is only
16455     // supported on 32-bit Windows, which isn't PIC.
16456     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16457     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16458   }
16459
16460   case Intrinsic::x86_seh_recoverfp: {
16461     SDValue FnOp = Op.getOperand(1);
16462     SDValue IncomingFPOp = Op.getOperand(2);
16463     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16464     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16465     if (!Fn)
16466       report_fatal_error(
16467           "llvm.x86.seh.recoverfp must take a function as the first argument");
16468     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16469   }
16470
16471   case Intrinsic::localaddress: {
16472     // Returns one of the stack, base, or frame pointer registers, depending on
16473     // which is used to reference local variables.
16474     MachineFunction &MF = DAG.getMachineFunction();
16475     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16476     unsigned Reg;
16477     if (RegInfo->hasBasePointer(MF))
16478       Reg = RegInfo->getBaseRegister();
16479     else // This function handles the SP or FP case.
16480       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16481     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16482   }
16483   }
16484 }
16485
16486 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16487                               SDValue Src, SDValue Mask, SDValue Base,
16488                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16489                               const X86Subtarget * Subtarget) {
16490   SDLoc dl(Op);
16491   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16492   if (!C)
16493     llvm_unreachable("Invalid scale type");
16494   unsigned ScaleVal = C->getZExtValue();
16495   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16496     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16497
16498   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16499   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16500                              Index.getSimpleValueType().getVectorNumElements());
16501   SDValue MaskInReg;
16502   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16503   if (MaskC)
16504     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16505   else {
16506     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16507                                      Mask.getValueType().getSizeInBits());
16508
16509     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16510     // are extracted by EXTRACT_SUBVECTOR.
16511     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16512                             DAG.getBitcast(BitcastVT, Mask),
16513                             DAG.getIntPtrConstant(0, dl));
16514   }
16515   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16516   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16517   SDValue Segment = DAG.getRegister(0, MVT::i32);
16518   if (Src.getOpcode() == ISD::UNDEF)
16519     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16520   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16521   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16522   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16523   return DAG.getMergeValues(RetOps, dl);
16524 }
16525
16526 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16527                                SDValue Src, SDValue Mask, SDValue Base,
16528                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16529   SDLoc dl(Op);
16530   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16531   if (!C)
16532     llvm_unreachable("Invalid scale type");
16533   unsigned ScaleVal = C->getZExtValue();
16534   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16535     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16536
16537   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16538   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16539   SDValue Segment = DAG.getRegister(0, MVT::i32);
16540   EVT MaskVT = MVT::getVectorVT(MVT::i1,
16541                              Index.getSimpleValueType().getVectorNumElements());
16542   SDValue MaskInReg;
16543   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16544   if (MaskC)
16545     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16546   else {
16547     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16548                                      Mask.getValueType().getSizeInBits());
16549
16550     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16551     // are extracted by EXTRACT_SUBVECTOR.
16552     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16553                             DAG.getBitcast(BitcastVT, Mask),
16554                             DAG.getIntPtrConstant(0, dl));
16555   }
16556   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16557   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16558   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16559   return SDValue(Res, 1);
16560 }
16561
16562 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16563                                SDValue Mask, SDValue Base, SDValue Index,
16564                                SDValue ScaleOp, SDValue Chain) {
16565   SDLoc dl(Op);
16566   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16567   assert(C && "Invalid scale type");
16568   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16569   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16570   SDValue Segment = DAG.getRegister(0, MVT::i32);
16571   EVT MaskVT =
16572     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16573   SDValue MaskInReg;
16574   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16575   if (MaskC)
16576     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16577   else
16578     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16579   //SDVTList VTs = DAG.getVTList(MVT::Other);
16580   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16581   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16582   return SDValue(Res, 0);
16583 }
16584
16585 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16586 // read performance monitor counters (x86_rdpmc).
16587 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16588                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16589                               SmallVectorImpl<SDValue> &Results) {
16590   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16591   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16592   SDValue LO, HI;
16593
16594   // The ECX register is used to select the index of the performance counter
16595   // to read.
16596   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16597                                    N->getOperand(2));
16598   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16599
16600   // Reads the content of a 64-bit performance counter and returns it in the
16601   // registers EDX:EAX.
16602   if (Subtarget->is64Bit()) {
16603     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16604     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16605                             LO.getValue(2));
16606   } else {
16607     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16608     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16609                             LO.getValue(2));
16610   }
16611   Chain = HI.getValue(1);
16612
16613   if (Subtarget->is64Bit()) {
16614     // The EAX register is loaded with the low-order 32 bits. The EDX register
16615     // is loaded with the supported high-order bits of the counter.
16616     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16617                               DAG.getConstant(32, DL, MVT::i8));
16618     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16619     Results.push_back(Chain);
16620     return;
16621   }
16622
16623   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16624   SDValue Ops[] = { LO, HI };
16625   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16626   Results.push_back(Pair);
16627   Results.push_back(Chain);
16628 }
16629
16630 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16631 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16632 // also used to custom lower READCYCLECOUNTER nodes.
16633 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16634                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16635                               SmallVectorImpl<SDValue> &Results) {
16636   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16637   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16638   SDValue LO, HI;
16639
16640   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16641   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16642   // and the EAX register is loaded with the low-order 32 bits.
16643   if (Subtarget->is64Bit()) {
16644     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16645     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16646                             LO.getValue(2));
16647   } else {
16648     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16649     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16650                             LO.getValue(2));
16651   }
16652   SDValue Chain = HI.getValue(1);
16653
16654   if (Opcode == X86ISD::RDTSCP_DAG) {
16655     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16656
16657     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16658     // the ECX register. Add 'ecx' explicitly to the chain.
16659     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16660                                      HI.getValue(2));
16661     // Explicitly store the content of ECX at the location passed in input
16662     // to the 'rdtscp' intrinsic.
16663     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16664                          MachinePointerInfo(), false, false, 0);
16665   }
16666
16667   if (Subtarget->is64Bit()) {
16668     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16669     // the EAX register is loaded with the low-order 32 bits.
16670     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16671                               DAG.getConstant(32, DL, MVT::i8));
16672     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16673     Results.push_back(Chain);
16674     return;
16675   }
16676
16677   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16678   SDValue Ops[] = { LO, HI };
16679   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16680   Results.push_back(Pair);
16681   Results.push_back(Chain);
16682 }
16683
16684 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16685                                      SelectionDAG &DAG) {
16686   SmallVector<SDValue, 2> Results;
16687   SDLoc DL(Op);
16688   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16689                           Results);
16690   return DAG.getMergeValues(Results, DL);
16691 }
16692
16693 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16694                                     SelectionDAG &DAG) {
16695   MachineFunction &MF = DAG.getMachineFunction();
16696   const Function *Fn = MF.getFunction();
16697   SDLoc dl(Op);
16698   SDValue Chain = Op.getOperand(0);
16699
16700   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16701          "using llvm.x86.seh.restoreframe requires a frame pointer");
16702
16703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16704   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16705
16706   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16707   unsigned FrameReg =
16708       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16709   unsigned SPReg = RegInfo->getStackRegister();
16710   unsigned SlotSize = RegInfo->getSlotSize();
16711
16712   // Get incoming EBP.
16713   SDValue IncomingEBP =
16714       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16715
16716   // SP is saved in the first field of every registration node, so load
16717   // [EBP-RegNodeSize] into SP.
16718   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16719   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16720                                DAG.getConstant(-RegNodeSize, dl, VT));
16721   SDValue NewSP =
16722       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16723                   false, VT.getScalarSizeInBits() / 8);
16724   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16725
16726   if (!RegInfo->needsStackRealignment(MF)) {
16727     // Adjust EBP to point back to the original frame position.
16728     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16729     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16730   } else {
16731     assert(RegInfo->hasBasePointer(MF) &&
16732            "functions with Win32 EH must use frame or base pointer register");
16733
16734     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16735     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16736     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16737
16738     // Reload the spilled EBP value, now that the stack and base pointers are
16739     // set up.
16740     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16741     X86FI->setHasSEHFramePtrSave(true);
16742     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16743     X86FI->setSEHFramePtrSaveIndex(FI);
16744     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16745                                 MachinePointerInfo(), false, false, false,
16746                                 VT.getScalarSizeInBits() / 8);
16747     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16748   }
16749
16750   return Chain;
16751 }
16752
16753 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16754 /// return truncate Store/MaskedStore Node
16755 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16756                                                SelectionDAG &DAG,
16757                                                MVT ElementType) {
16758   SDLoc dl(Op);
16759   SDValue Mask = Op.getOperand(4);
16760   SDValue DataToTruncate = Op.getOperand(3);
16761   SDValue Addr = Op.getOperand(2);
16762   SDValue Chain = Op.getOperand(0);
16763
16764   EVT VT  = DataToTruncate.getValueType();
16765   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16766                              ElementType, VT.getVectorNumElements());
16767
16768   if (isAllOnes(Mask)) // return just a truncate store
16769     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16770                              MachinePointerInfo(), SVT, false, false,
16771                              SVT.getScalarSizeInBits()/8);
16772
16773   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16774                                 MVT::i1, VT.getVectorNumElements());
16775   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16776                                    Mask.getValueType().getSizeInBits());
16777   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16778   // are extracted by EXTRACT_SUBVECTOR.
16779   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16780                               DAG.getBitcast(BitcastVT, Mask),
16781                               DAG.getIntPtrConstant(0, dl));
16782
16783   MachineMemOperand *MMO = DAG.getMachineFunction().
16784     getMachineMemOperand(MachinePointerInfo(),
16785                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16786                          SVT.getScalarSizeInBits()/8);
16787
16788   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16789                             VMask, SVT, MMO, true);
16790 }
16791
16792 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16793                                       SelectionDAG &DAG) {
16794   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16795
16796   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16797   if (!IntrData) {
16798     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16799       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16800     return SDValue();
16801   }
16802
16803   SDLoc dl(Op);
16804   switch(IntrData->Type) {
16805   default:
16806     llvm_unreachable("Unknown Intrinsic Type");
16807     break;
16808   case RDSEED:
16809   case RDRAND: {
16810     // Emit the node with the right value type.
16811     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16812     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16813
16814     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16815     // Otherwise return the value from Rand, which is always 0, casted to i32.
16816     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16817                       DAG.getConstant(1, dl, Op->getValueType(1)),
16818                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16819                       SDValue(Result.getNode(), 1) };
16820     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16821                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16822                                   Ops);
16823
16824     // Return { result, isValid, chain }.
16825     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16826                        SDValue(Result.getNode(), 2));
16827   }
16828   case GATHER: {
16829   //gather(v1, mask, index, base, scale);
16830     SDValue Chain = Op.getOperand(0);
16831     SDValue Src   = Op.getOperand(2);
16832     SDValue Base  = Op.getOperand(3);
16833     SDValue Index = Op.getOperand(4);
16834     SDValue Mask  = Op.getOperand(5);
16835     SDValue Scale = Op.getOperand(6);
16836     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16837                          Chain, Subtarget);
16838   }
16839   case SCATTER: {
16840   //scatter(base, mask, index, v1, scale);
16841     SDValue Chain = Op.getOperand(0);
16842     SDValue Base  = Op.getOperand(2);
16843     SDValue Mask  = Op.getOperand(3);
16844     SDValue Index = Op.getOperand(4);
16845     SDValue Src   = Op.getOperand(5);
16846     SDValue Scale = Op.getOperand(6);
16847     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16848                           Scale, Chain);
16849   }
16850   case PREFETCH: {
16851     SDValue Hint = Op.getOperand(6);
16852     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16853     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16854     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16855     SDValue Chain = Op.getOperand(0);
16856     SDValue Mask  = Op.getOperand(2);
16857     SDValue Index = Op.getOperand(3);
16858     SDValue Base  = Op.getOperand(4);
16859     SDValue Scale = Op.getOperand(5);
16860     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16861   }
16862   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16863   case RDTSC: {
16864     SmallVector<SDValue, 2> Results;
16865     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16866                             Results);
16867     return DAG.getMergeValues(Results, dl);
16868   }
16869   // Read Performance Monitoring Counters.
16870   case RDPMC: {
16871     SmallVector<SDValue, 2> Results;
16872     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16873     return DAG.getMergeValues(Results, dl);
16874   }
16875   // XTEST intrinsics.
16876   case XTEST: {
16877     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16878     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16879     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16880                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16881                                 InTrans);
16882     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16883     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16884                        Ret, SDValue(InTrans.getNode(), 1));
16885   }
16886   // ADC/ADCX/SBB
16887   case ADX: {
16888     SmallVector<SDValue, 2> Results;
16889     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16890     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16891     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16892                                 DAG.getConstant(-1, dl, MVT::i8));
16893     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16894                               Op.getOperand(4), GenCF.getValue(1));
16895     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16896                                  Op.getOperand(5), MachinePointerInfo(),
16897                                  false, false, 0);
16898     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16899                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16900                                 Res.getValue(1));
16901     Results.push_back(SetCC);
16902     Results.push_back(Store);
16903     return DAG.getMergeValues(Results, dl);
16904   }
16905   case COMPRESS_TO_MEM: {
16906     SDLoc dl(Op);
16907     SDValue Mask = Op.getOperand(4);
16908     SDValue DataToCompress = Op.getOperand(3);
16909     SDValue Addr = Op.getOperand(2);
16910     SDValue Chain = Op.getOperand(0);
16911
16912     EVT VT = DataToCompress.getValueType();
16913     if (isAllOnes(Mask)) // return just a store
16914       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16915                           MachinePointerInfo(), false, false,
16916                           VT.getScalarSizeInBits()/8);
16917
16918     SDValue Compressed =
16919       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16920                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16921     return DAG.getStore(Chain, dl, Compressed, Addr,
16922                         MachinePointerInfo(), false, false,
16923                         VT.getScalarSizeInBits()/8);
16924   }
16925   case TRUNCATE_TO_MEM_VI8:
16926     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16927   case TRUNCATE_TO_MEM_VI16:
16928     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16929   case TRUNCATE_TO_MEM_VI32:
16930     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16931   case EXPAND_FROM_MEM: {
16932     SDLoc dl(Op);
16933     SDValue Mask = Op.getOperand(4);
16934     SDValue PassThru = Op.getOperand(3);
16935     SDValue Addr = Op.getOperand(2);
16936     SDValue Chain = Op.getOperand(0);
16937     EVT VT = Op.getValueType();
16938
16939     if (isAllOnes(Mask)) // return just a load
16940       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16941                          false, VT.getScalarSizeInBits()/8);
16942
16943     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16944                                        false, false, false,
16945                                        VT.getScalarSizeInBits()/8);
16946
16947     SDValue Results[] = {
16948       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16949                            Mask, PassThru, Subtarget, DAG), Chain};
16950     return DAG.getMergeValues(Results, dl);
16951   }
16952   }
16953 }
16954
16955 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16956                                            SelectionDAG &DAG) const {
16957   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16958   MFI->setReturnAddressIsTaken(true);
16959
16960   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16961     return SDValue();
16962
16963   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16964   SDLoc dl(Op);
16965   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16966
16967   if (Depth > 0) {
16968     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16969     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16970     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16971     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16972                        DAG.getNode(ISD::ADD, dl, PtrVT,
16973                                    FrameAddr, Offset),
16974                        MachinePointerInfo(), false, false, false, 0);
16975   }
16976
16977   // Just load the return address.
16978   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16979   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16980                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16981 }
16982
16983 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16984   MachineFunction &MF = DAG.getMachineFunction();
16985   MachineFrameInfo *MFI = MF.getFrameInfo();
16986   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16987   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16988   EVT VT = Op.getValueType();
16989
16990   MFI->setFrameAddressIsTaken(true);
16991
16992   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16993     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16994     // is not possible to crawl up the stack without looking at the unwind codes
16995     // simultaneously.
16996     int FrameAddrIndex = FuncInfo->getFAIndex();
16997     if (!FrameAddrIndex) {
16998       // Set up a frame object for the return address.
16999       unsigned SlotSize = RegInfo->getSlotSize();
17000       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17001           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17002       FuncInfo->setFAIndex(FrameAddrIndex);
17003     }
17004     return DAG.getFrameIndex(FrameAddrIndex, VT);
17005   }
17006
17007   unsigned FrameReg =
17008       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17009   SDLoc dl(Op);  // FIXME probably not meaningful
17010   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17011   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17012           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17013          "Invalid Frame Register!");
17014   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17015   while (Depth--)
17016     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17017                             MachinePointerInfo(),
17018                             false, false, false, 0);
17019   return FrameAddr;
17020 }
17021
17022 // FIXME? Maybe this could be a TableGen attribute on some registers and
17023 // this table could be generated automatically from RegInfo.
17024 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17025                                               SelectionDAG &DAG) const {
17026   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17027   const MachineFunction &MF = DAG.getMachineFunction();
17028
17029   unsigned Reg = StringSwitch<unsigned>(RegName)
17030                        .Case("esp", X86::ESP)
17031                        .Case("rsp", X86::RSP)
17032                        .Case("ebp", X86::EBP)
17033                        .Case("rbp", X86::RBP)
17034                        .Default(0);
17035
17036   if (Reg == X86::EBP || Reg == X86::RBP) {
17037     if (!TFI.hasFP(MF))
17038       report_fatal_error("register " + StringRef(RegName) +
17039                          " is allocatable: function has no frame pointer");
17040 #ifndef NDEBUG
17041     else {
17042       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17043       unsigned FrameReg =
17044           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17045       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17046              "Invalid Frame Register!");
17047     }
17048 #endif
17049   }
17050
17051   if (Reg)
17052     return Reg;
17053
17054   report_fatal_error("Invalid register name global variable");
17055 }
17056
17057 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17058                                                      SelectionDAG &DAG) const {
17059   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17060   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17061 }
17062
17063 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17064   SDValue Chain     = Op.getOperand(0);
17065   SDValue Offset    = Op.getOperand(1);
17066   SDValue Handler   = Op.getOperand(2);
17067   SDLoc dl      (Op);
17068
17069   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17070   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17071   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17072   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17073           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17074          "Invalid Frame Register!");
17075   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17076   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17077
17078   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17079                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17080                                                        dl));
17081   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17082   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17083                        false, false, 0);
17084   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17085
17086   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17087                      DAG.getRegister(StoreAddrReg, PtrVT));
17088 }
17089
17090 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17091                                                SelectionDAG &DAG) const {
17092   SDLoc DL(Op);
17093   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17094                      DAG.getVTList(MVT::i32, MVT::Other),
17095                      Op.getOperand(0), Op.getOperand(1));
17096 }
17097
17098 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17099                                                 SelectionDAG &DAG) const {
17100   SDLoc DL(Op);
17101   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17102                      Op.getOperand(0), Op.getOperand(1));
17103 }
17104
17105 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17106   return Op.getOperand(0);
17107 }
17108
17109 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17110                                                 SelectionDAG &DAG) const {
17111   SDValue Root = Op.getOperand(0);
17112   SDValue Trmp = Op.getOperand(1); // trampoline
17113   SDValue FPtr = Op.getOperand(2); // nested function
17114   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17115   SDLoc dl (Op);
17116
17117   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17118   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17119
17120   if (Subtarget->is64Bit()) {
17121     SDValue OutChains[6];
17122
17123     // Large code-model.
17124     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17125     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17126
17127     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17128     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17129
17130     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17131
17132     // Load the pointer to the nested function into R11.
17133     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17134     SDValue Addr = Trmp;
17135     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17136                                 Addr, MachinePointerInfo(TrmpAddr),
17137                                 false, false, 0);
17138
17139     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17140                        DAG.getConstant(2, dl, MVT::i64));
17141     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17142                                 MachinePointerInfo(TrmpAddr, 2),
17143                                 false, false, 2);
17144
17145     // Load the 'nest' parameter value into R10.
17146     // R10 is specified in X86CallingConv.td
17147     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17148     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17149                        DAG.getConstant(10, dl, MVT::i64));
17150     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17151                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17152                                 false, false, 0);
17153
17154     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17155                        DAG.getConstant(12, dl, MVT::i64));
17156     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17157                                 MachinePointerInfo(TrmpAddr, 12),
17158                                 false, false, 2);
17159
17160     // Jump to the nested function.
17161     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17162     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17163                        DAG.getConstant(20, dl, MVT::i64));
17164     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17165                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17166                                 false, false, 0);
17167
17168     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17169     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17170                        DAG.getConstant(22, dl, MVT::i64));
17171     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17172                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17173                                 false, false, 0);
17174
17175     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17176   } else {
17177     const Function *Func =
17178       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17179     CallingConv::ID CC = Func->getCallingConv();
17180     unsigned NestReg;
17181
17182     switch (CC) {
17183     default:
17184       llvm_unreachable("Unsupported calling convention");
17185     case CallingConv::C:
17186     case CallingConv::X86_StdCall: {
17187       // Pass 'nest' parameter in ECX.
17188       // Must be kept in sync with X86CallingConv.td
17189       NestReg = X86::ECX;
17190
17191       // Check that ECX wasn't needed by an 'inreg' parameter.
17192       FunctionType *FTy = Func->getFunctionType();
17193       const AttributeSet &Attrs = Func->getAttributes();
17194
17195       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17196         unsigned InRegCount = 0;
17197         unsigned Idx = 1;
17198
17199         for (FunctionType::param_iterator I = FTy->param_begin(),
17200              E = FTy->param_end(); I != E; ++I, ++Idx)
17201           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17202             auto &DL = DAG.getDataLayout();
17203             // FIXME: should only count parameters that are lowered to integers.
17204             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17205           }
17206
17207         if (InRegCount > 2) {
17208           report_fatal_error("Nest register in use - reduce number of inreg"
17209                              " parameters!");
17210         }
17211       }
17212       break;
17213     }
17214     case CallingConv::X86_FastCall:
17215     case CallingConv::X86_ThisCall:
17216     case CallingConv::Fast:
17217       // Pass 'nest' parameter in EAX.
17218       // Must be kept in sync with X86CallingConv.td
17219       NestReg = X86::EAX;
17220       break;
17221     }
17222
17223     SDValue OutChains[4];
17224     SDValue Addr, Disp;
17225
17226     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17227                        DAG.getConstant(10, dl, MVT::i32));
17228     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17229
17230     // This is storing the opcode for MOV32ri.
17231     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17232     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17233     OutChains[0] = DAG.getStore(Root, dl,
17234                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17235                                 Trmp, MachinePointerInfo(TrmpAddr),
17236                                 false, false, 0);
17237
17238     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17239                        DAG.getConstant(1, dl, MVT::i32));
17240     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17241                                 MachinePointerInfo(TrmpAddr, 1),
17242                                 false, false, 1);
17243
17244     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17245     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17246                        DAG.getConstant(5, dl, MVT::i32));
17247     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17248                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17249                                 false, false, 1);
17250
17251     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17252                        DAG.getConstant(6, dl, MVT::i32));
17253     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17254                                 MachinePointerInfo(TrmpAddr, 6),
17255                                 false, false, 1);
17256
17257     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17258   }
17259 }
17260
17261 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17262                                             SelectionDAG &DAG) const {
17263   /*
17264    The rounding mode is in bits 11:10 of FPSR, and has the following
17265    settings:
17266      00 Round to nearest
17267      01 Round to -inf
17268      10 Round to +inf
17269      11 Round to 0
17270
17271   FLT_ROUNDS, on the other hand, expects the following:
17272     -1 Undefined
17273      0 Round to 0
17274      1 Round to nearest
17275      2 Round to +inf
17276      3 Round to -inf
17277
17278   To perform the conversion, we do:
17279     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17280   */
17281
17282   MachineFunction &MF = DAG.getMachineFunction();
17283   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17284   unsigned StackAlignment = TFI.getStackAlignment();
17285   MVT VT = Op.getSimpleValueType();
17286   SDLoc DL(Op);
17287
17288   // Save FP Control Word to stack slot
17289   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17290   SDValue StackSlot =
17291       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17292
17293   MachineMemOperand *MMO =
17294       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17295                               MachineMemOperand::MOStore, 2, 2);
17296
17297   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17298   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17299                                           DAG.getVTList(MVT::Other),
17300                                           Ops, MVT::i16, MMO);
17301
17302   // Load FP Control Word from stack slot
17303   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17304                             MachinePointerInfo(), false, false, false, 0);
17305
17306   // Transform as necessary
17307   SDValue CWD1 =
17308     DAG.getNode(ISD::SRL, DL, MVT::i16,
17309                 DAG.getNode(ISD::AND, DL, MVT::i16,
17310                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17311                 DAG.getConstant(11, DL, MVT::i8));
17312   SDValue CWD2 =
17313     DAG.getNode(ISD::SRL, DL, MVT::i16,
17314                 DAG.getNode(ISD::AND, DL, MVT::i16,
17315                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17316                 DAG.getConstant(9, DL, MVT::i8));
17317
17318   SDValue RetVal =
17319     DAG.getNode(ISD::AND, DL, MVT::i16,
17320                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17321                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17322                             DAG.getConstant(1, DL, MVT::i16)),
17323                 DAG.getConstant(3, DL, MVT::i16));
17324
17325   return DAG.getNode((VT.getSizeInBits() < 16 ?
17326                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17327 }
17328
17329 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17330   MVT VT = Op.getSimpleValueType();
17331   EVT OpVT = VT;
17332   unsigned NumBits = VT.getSizeInBits();
17333   SDLoc dl(Op);
17334
17335   Op = Op.getOperand(0);
17336   if (VT == MVT::i8) {
17337     // Zero extend to i32 since there is not an i8 bsr.
17338     OpVT = MVT::i32;
17339     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17340   }
17341
17342   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17343   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17344   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17345
17346   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17347   SDValue Ops[] = {
17348     Op,
17349     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17350     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17351     Op.getValue(1)
17352   };
17353   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17354
17355   // Finally xor with NumBits-1.
17356   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17357                    DAG.getConstant(NumBits - 1, dl, OpVT));
17358
17359   if (VT == MVT::i8)
17360     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17361   return Op;
17362 }
17363
17364 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17365   MVT VT = Op.getSimpleValueType();
17366   EVT OpVT = VT;
17367   unsigned NumBits = VT.getSizeInBits();
17368   SDLoc dl(Op);
17369
17370   Op = Op.getOperand(0);
17371   if (VT == MVT::i8) {
17372     // Zero extend to i32 since there is not an i8 bsr.
17373     OpVT = MVT::i32;
17374     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17375   }
17376
17377   // Issue a bsr (scan bits in reverse).
17378   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17379   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17380
17381   // And xor with NumBits-1.
17382   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17383                    DAG.getConstant(NumBits - 1, dl, OpVT));
17384
17385   if (VT == MVT::i8)
17386     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17387   return Op;
17388 }
17389
17390 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17391   MVT VT = Op.getSimpleValueType();
17392   unsigned NumBits = VT.getScalarSizeInBits();
17393   SDLoc dl(Op);
17394
17395   if (VT.isVector()) {
17396     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17397
17398     SDValue N0 = Op.getOperand(0);
17399     SDValue Zero = DAG.getConstant(0, dl, VT);
17400
17401     // lsb(x) = (x & -x)
17402     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17403                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17404
17405     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17406     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17407         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17408       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17409       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17410                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17411     }
17412
17413     // cttz(x) = ctpop(lsb - 1)
17414     SDValue One = DAG.getConstant(1, dl, VT);
17415     return DAG.getNode(ISD::CTPOP, dl, VT,
17416                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17417   }
17418
17419   assert(Op.getOpcode() == ISD::CTTZ &&
17420          "Only scalar CTTZ requires custom lowering");
17421
17422   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17423   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17424   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17425
17426   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17427   SDValue Ops[] = {
17428     Op,
17429     DAG.getConstant(NumBits, dl, VT),
17430     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17431     Op.getValue(1)
17432   };
17433   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17434 }
17435
17436 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17437 // ones, and then concatenate the result back.
17438 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17439   MVT VT = Op.getSimpleValueType();
17440
17441   assert(VT.is256BitVector() && VT.isInteger() &&
17442          "Unsupported value type for operation");
17443
17444   unsigned NumElems = VT.getVectorNumElements();
17445   SDLoc dl(Op);
17446
17447   // Extract the LHS vectors
17448   SDValue LHS = Op.getOperand(0);
17449   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17450   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17451
17452   // Extract the RHS vectors
17453   SDValue RHS = Op.getOperand(1);
17454   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17455   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17456
17457   MVT EltVT = VT.getVectorElementType();
17458   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17459
17460   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17461                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17462                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17463 }
17464
17465 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17466   if (Op.getValueType() == MVT::i1)
17467     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17468                        Op.getOperand(0), Op.getOperand(1));
17469   assert(Op.getSimpleValueType().is256BitVector() &&
17470          Op.getSimpleValueType().isInteger() &&
17471          "Only handle AVX 256-bit vector integer operation");
17472   return Lower256IntArith(Op, DAG);
17473 }
17474
17475 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17476   if (Op.getValueType() == MVT::i1)
17477     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17478                        Op.getOperand(0), Op.getOperand(1));
17479   assert(Op.getSimpleValueType().is256BitVector() &&
17480          Op.getSimpleValueType().isInteger() &&
17481          "Only handle AVX 256-bit vector integer operation");
17482   return Lower256IntArith(Op, DAG);
17483 }
17484
17485 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17486   assert(Op.getSimpleValueType().is256BitVector() &&
17487          Op.getSimpleValueType().isInteger() &&
17488          "Only handle AVX 256-bit vector integer operation");
17489   return Lower256IntArith(Op, DAG);
17490 }
17491
17492 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17493                         SelectionDAG &DAG) {
17494   SDLoc dl(Op);
17495   MVT VT = Op.getSimpleValueType();
17496
17497   if (VT == MVT::i1)
17498     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17499
17500   // Decompose 256-bit ops into smaller 128-bit ops.
17501   if (VT.is256BitVector() && !Subtarget->hasInt256())
17502     return Lower256IntArith(Op, DAG);
17503
17504   SDValue A = Op.getOperand(0);
17505   SDValue B = Op.getOperand(1);
17506
17507   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17508   // pairs, multiply and truncate.
17509   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17510     if (Subtarget->hasInt256()) {
17511       if (VT == MVT::v32i8) {
17512         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17513         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17514         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17515         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17516         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17517         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17518         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17519         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17520                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17521                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17522       }
17523
17524       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17525       return DAG.getNode(
17526           ISD::TRUNCATE, dl, VT,
17527           DAG.getNode(ISD::MUL, dl, ExVT,
17528                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17529                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17530     }
17531
17532     assert(VT == MVT::v16i8 &&
17533            "Pre-AVX2 support only supports v16i8 multiplication");
17534     MVT ExVT = MVT::v8i16;
17535
17536     // Extract the lo parts and sign extend to i16
17537     SDValue ALo, BLo;
17538     if (Subtarget->hasSSE41()) {
17539       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17540       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17541     } else {
17542       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17543                               -1, 4, -1, 5, -1, 6, -1, 7};
17544       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17545       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17546       ALo = DAG.getBitcast(ExVT, ALo);
17547       BLo = DAG.getBitcast(ExVT, BLo);
17548       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17549       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17550     }
17551
17552     // Extract the hi parts and sign extend to i16
17553     SDValue AHi, BHi;
17554     if (Subtarget->hasSSE41()) {
17555       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17556                               -1, -1, -1, -1, -1, -1, -1, -1};
17557       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17558       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17559       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17560       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17561     } else {
17562       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17563                               -1, 12, -1, 13, -1, 14, -1, 15};
17564       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17565       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17566       AHi = DAG.getBitcast(ExVT, AHi);
17567       BHi = DAG.getBitcast(ExVT, BHi);
17568       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17569       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17570     }
17571
17572     // Multiply, mask the lower 8bits of the lo/hi results and pack
17573     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17574     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17575     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17576     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17577     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17578   }
17579
17580   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17581   if (VT == MVT::v4i32) {
17582     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17583            "Should not custom lower when pmuldq is available!");
17584
17585     // Extract the odd parts.
17586     static const int UnpackMask[] = { 1, -1, 3, -1 };
17587     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17588     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17589
17590     // Multiply the even parts.
17591     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17592     // Now multiply odd parts.
17593     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17594
17595     Evens = DAG.getBitcast(VT, Evens);
17596     Odds = DAG.getBitcast(VT, Odds);
17597
17598     // Merge the two vectors back together with a shuffle. This expands into 2
17599     // shuffles.
17600     static const int ShufMask[] = { 0, 4, 2, 6 };
17601     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17602   }
17603
17604   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17605          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17606
17607   //  Ahi = psrlqi(a, 32);
17608   //  Bhi = psrlqi(b, 32);
17609   //
17610   //  AloBlo = pmuludq(a, b);
17611   //  AloBhi = pmuludq(a, Bhi);
17612   //  AhiBlo = pmuludq(Ahi, b);
17613
17614   //  AloBhi = psllqi(AloBhi, 32);
17615   //  AhiBlo = psllqi(AhiBlo, 32);
17616   //  return AloBlo + AloBhi + AhiBlo;
17617
17618   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17619   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17620
17621   SDValue AhiBlo = Ahi;
17622   SDValue AloBhi = Bhi;
17623   // Bit cast to 32-bit vectors for MULUDQ
17624   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17625                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17626   A = DAG.getBitcast(MulVT, A);
17627   B = DAG.getBitcast(MulVT, B);
17628   Ahi = DAG.getBitcast(MulVT, Ahi);
17629   Bhi = DAG.getBitcast(MulVT, Bhi);
17630
17631   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17632   // After shifting right const values the result may be all-zero.
17633   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17634     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17635     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17636   }
17637   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17638     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17639     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17640   }
17641
17642   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17643   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17644 }
17645
17646 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17647   assert(Subtarget->isTargetWin64() && "Unexpected target");
17648   EVT VT = Op.getValueType();
17649   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17650          "Unexpected return type for lowering");
17651
17652   RTLIB::Libcall LC;
17653   bool isSigned;
17654   switch (Op->getOpcode()) {
17655   default: llvm_unreachable("Unexpected request for libcall!");
17656   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17657   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17658   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17659   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17660   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17661   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17662   }
17663
17664   SDLoc dl(Op);
17665   SDValue InChain = DAG.getEntryNode();
17666
17667   TargetLowering::ArgListTy Args;
17668   TargetLowering::ArgListEntry Entry;
17669   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17670     EVT ArgVT = Op->getOperand(i).getValueType();
17671     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17672            "Unexpected argument type for lowering");
17673     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17674     Entry.Node = StackPtr;
17675     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17676                            false, false, 16);
17677     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17678     Entry.Ty = PointerType::get(ArgTy,0);
17679     Entry.isSExt = false;
17680     Entry.isZExt = false;
17681     Args.push_back(Entry);
17682   }
17683
17684   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17685                                          getPointerTy(DAG.getDataLayout()));
17686
17687   TargetLowering::CallLoweringInfo CLI(DAG);
17688   CLI.setDebugLoc(dl).setChain(InChain)
17689     .setCallee(getLibcallCallingConv(LC),
17690                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17691                Callee, std::move(Args), 0)
17692     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17693
17694   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17695   return DAG.getBitcast(VT, CallInfo.first);
17696 }
17697
17698 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17699                              SelectionDAG &DAG) {
17700   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17701   EVT VT = Op0.getValueType();
17702   SDLoc dl(Op);
17703
17704   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17705          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17706
17707   // PMULxD operations multiply each even value (starting at 0) of LHS with
17708   // the related value of RHS and produce a widen result.
17709   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17710   // => <2 x i64> <ae|cg>
17711   //
17712   // In other word, to have all the results, we need to perform two PMULxD:
17713   // 1. one with the even values.
17714   // 2. one with the odd values.
17715   // To achieve #2, with need to place the odd values at an even position.
17716   //
17717   // Place the odd value at an even position (basically, shift all values 1
17718   // step to the left):
17719   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17720   // <a|b|c|d> => <b|undef|d|undef>
17721   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17722   // <e|f|g|h> => <f|undef|h|undef>
17723   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17724
17725   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17726   // ints.
17727   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17728   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17729   unsigned Opcode =
17730       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17731   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17732   // => <2 x i64> <ae|cg>
17733   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17734   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17735   // => <2 x i64> <bf|dh>
17736   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17737
17738   // Shuffle it back into the right order.
17739   SDValue Highs, Lows;
17740   if (VT == MVT::v8i32) {
17741     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17742     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17743     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17744     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17745   } else {
17746     const int HighMask[] = {1, 5, 3, 7};
17747     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17748     const int LowMask[] = {0, 4, 2, 6};
17749     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17750   }
17751
17752   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17753   // unsigned multiply.
17754   if (IsSigned && !Subtarget->hasSSE41()) {
17755     SDValue ShAmt = DAG.getConstant(
17756         31, dl,
17757         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17758     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17759                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17760     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17761                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17762
17763     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17764     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17765   }
17766
17767   // The first result of MUL_LOHI is actually the low value, followed by the
17768   // high value.
17769   SDValue Ops[] = {Lows, Highs};
17770   return DAG.getMergeValues(Ops, dl);
17771 }
17772
17773 // Return true if the required (according to Opcode) shift-imm form is natively
17774 // supported by the Subtarget
17775 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17776                                         unsigned Opcode) {
17777   if (VT.getScalarSizeInBits() < 16)
17778     return false;
17779
17780   if (VT.is512BitVector() &&
17781       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17782     return true;
17783
17784   bool LShift = VT.is128BitVector() ||
17785     (VT.is256BitVector() && Subtarget->hasInt256());
17786
17787   bool AShift = LShift && (Subtarget->hasVLX() ||
17788     (VT != MVT::v2i64 && VT != MVT::v4i64));
17789   return (Opcode == ISD::SRA) ? AShift : LShift;
17790 }
17791
17792 // The shift amount is a variable, but it is the same for all vector lanes.
17793 // These instructions are defined together with shift-immediate.
17794 static
17795 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17796                                       unsigned Opcode) {
17797   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17798 }
17799
17800 // Return true if the required (according to Opcode) variable-shift form is
17801 // natively supported by the Subtarget
17802 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17803                                     unsigned Opcode) {
17804
17805   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17806     return false;
17807
17808   // vXi16 supported only on AVX-512, BWI
17809   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17810     return false;
17811
17812   if (VT.is512BitVector() || Subtarget->hasVLX())
17813     return true;
17814
17815   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17816   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17817   return (Opcode == ISD::SRA) ? AShift : LShift;
17818 }
17819
17820 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17821                                          const X86Subtarget *Subtarget) {
17822   MVT VT = Op.getSimpleValueType();
17823   SDLoc dl(Op);
17824   SDValue R = Op.getOperand(0);
17825   SDValue Amt = Op.getOperand(1);
17826
17827   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17828     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17829
17830   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17831     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17832     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17833     SDValue Ex = DAG.getBitcast(ExVT, R);
17834
17835     if (ShiftAmt >= 32) {
17836       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17837       SDValue Upper =
17838           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17839       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17840                                                  ShiftAmt - 32, DAG);
17841       if (VT == MVT::v2i64)
17842         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17843       if (VT == MVT::v4i64)
17844         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17845                                   {9, 1, 11, 3, 13, 5, 15, 7});
17846     } else {
17847       // SRA upper i32, SHL whole i64 and select lower i32.
17848       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17849                                                  ShiftAmt, DAG);
17850       SDValue Lower =
17851           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17852       Lower = DAG.getBitcast(ExVT, Lower);
17853       if (VT == MVT::v2i64)
17854         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17855       if (VT == MVT::v4i64)
17856         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17857                                   {8, 1, 10, 3, 12, 5, 14, 7});
17858     }
17859     return DAG.getBitcast(VT, Ex);
17860   };
17861
17862   // Optimize shl/srl/sra with constant shift amount.
17863   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17864     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17865       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17866
17867       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17868         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17869
17870       // i64 SRA needs to be performed as partial shifts.
17871       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17872           Op.getOpcode() == ISD::SRA)
17873         return ArithmeticShiftRight64(ShiftAmt);
17874
17875       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17876         unsigned NumElts = VT.getVectorNumElements();
17877         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17878
17879         if (Op.getOpcode() == ISD::SHL) {
17880           // Simple i8 add case
17881           if (ShiftAmt == 1)
17882             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17883
17884           // Make a large shift.
17885           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17886                                                    R, ShiftAmt, DAG);
17887           SHL = DAG.getBitcast(VT, SHL);
17888           // Zero out the rightmost bits.
17889           SmallVector<SDValue, 32> V(
17890               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17891           return DAG.getNode(ISD::AND, dl, VT, SHL,
17892                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17893         }
17894         if (Op.getOpcode() == ISD::SRL) {
17895           // Make a large shift.
17896           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17897                                                    R, ShiftAmt, DAG);
17898           SRL = DAG.getBitcast(VT, SRL);
17899           // Zero out the leftmost bits.
17900           SmallVector<SDValue, 32> V(
17901               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17902           return DAG.getNode(ISD::AND, dl, VT, SRL,
17903                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17904         }
17905         if (Op.getOpcode() == ISD::SRA) {
17906           if (ShiftAmt == 7) {
17907             // ashr(R, 7)  === cmp_slt(R, 0)
17908             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17909             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17910           }
17911
17912           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17913           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17914           SmallVector<SDValue, 32> V(NumElts,
17915                                      DAG.getConstant(128 >> ShiftAmt, dl,
17916                                                      MVT::i8));
17917           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17918           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17919           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17920           return Res;
17921         }
17922         llvm_unreachable("Unknown shift opcode.");
17923       }
17924     }
17925   }
17926
17927   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17928   if (!Subtarget->is64Bit() &&
17929       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17930
17931     // Peek through any splat that was introduced for i64 shift vectorization.
17932     int SplatIndex = -1;
17933     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17934       if (SVN->isSplat()) {
17935         SplatIndex = SVN->getSplatIndex();
17936         Amt = Amt.getOperand(0);
17937         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17938                "Splat shuffle referencing second operand");
17939       }
17940
17941     if (Amt.getOpcode() != ISD::BITCAST ||
17942         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17943       return SDValue();
17944
17945     Amt = Amt.getOperand(0);
17946     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17947                      VT.getVectorNumElements();
17948     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17949     uint64_t ShiftAmt = 0;
17950     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17951     for (unsigned i = 0; i != Ratio; ++i) {
17952       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17953       if (!C)
17954         return SDValue();
17955       // 6 == Log2(64)
17956       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17957     }
17958
17959     // Check remaining shift amounts (if not a splat).
17960     if (SplatIndex < 0) {
17961       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17962         uint64_t ShAmt = 0;
17963         for (unsigned j = 0; j != Ratio; ++j) {
17964           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17965           if (!C)
17966             return SDValue();
17967           // 6 == Log2(64)
17968           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17969         }
17970         if (ShAmt != ShiftAmt)
17971           return SDValue();
17972       }
17973     }
17974
17975     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17976       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17977
17978     if (Op.getOpcode() == ISD::SRA)
17979       return ArithmeticShiftRight64(ShiftAmt);
17980   }
17981
17982   return SDValue();
17983 }
17984
17985 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17986                                         const X86Subtarget* Subtarget) {
17987   MVT VT = Op.getSimpleValueType();
17988   SDLoc dl(Op);
17989   SDValue R = Op.getOperand(0);
17990   SDValue Amt = Op.getOperand(1);
17991
17992   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17993     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17994
17995   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17996     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17997
17998   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17999     SDValue BaseShAmt;
18000     EVT EltVT = VT.getVectorElementType();
18001
18002     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18003       // Check if this build_vector node is doing a splat.
18004       // If so, then set BaseShAmt equal to the splat value.
18005       BaseShAmt = BV->getSplatValue();
18006       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18007         BaseShAmt = SDValue();
18008     } else {
18009       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18010         Amt = Amt.getOperand(0);
18011
18012       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18013       if (SVN && SVN->isSplat()) {
18014         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18015         SDValue InVec = Amt.getOperand(0);
18016         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18017           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18018                  "Unexpected shuffle index found!");
18019           BaseShAmt = InVec.getOperand(SplatIdx);
18020         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18021            if (ConstantSDNode *C =
18022                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18023              if (C->getZExtValue() == SplatIdx)
18024                BaseShAmt = InVec.getOperand(1);
18025            }
18026         }
18027
18028         if (!BaseShAmt)
18029           // Avoid introducing an extract element from a shuffle.
18030           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18031                                   DAG.getIntPtrConstant(SplatIdx, dl));
18032       }
18033     }
18034
18035     if (BaseShAmt.getNode()) {
18036       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18037       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18038         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18039       else if (EltVT.bitsLT(MVT::i32))
18040         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18041
18042       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18043     }
18044   }
18045
18046   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18047   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18048       Amt.getOpcode() == ISD::BITCAST &&
18049       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18050     Amt = Amt.getOperand(0);
18051     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18052                      VT.getVectorNumElements();
18053     std::vector<SDValue> Vals(Ratio);
18054     for (unsigned i = 0; i != Ratio; ++i)
18055       Vals[i] = Amt.getOperand(i);
18056     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18057       for (unsigned j = 0; j != Ratio; ++j)
18058         if (Vals[j] != Amt.getOperand(i + j))
18059           return SDValue();
18060     }
18061
18062     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18063       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18064   }
18065   return SDValue();
18066 }
18067
18068 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18069                           SelectionDAG &DAG) {
18070   MVT VT = Op.getSimpleValueType();
18071   SDLoc dl(Op);
18072   SDValue R = Op.getOperand(0);
18073   SDValue Amt = Op.getOperand(1);
18074
18075   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18076   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18077
18078   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18079     return V;
18080
18081   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18082       return V;
18083
18084   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18085     return Op;
18086
18087   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18088   // shifts per-lane and then shuffle the partial results back together.
18089   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18090     // Splat the shift amounts so the scalar shifts above will catch it.
18091     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18092     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18093     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18094     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18095     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18096   }
18097
18098   // i64 vector arithmetic shift can be emulated with the transform:
18099   // M = lshr(SIGN_BIT, Amt)
18100   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18101   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18102       Op.getOpcode() == ISD::SRA) {
18103     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18104     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18105     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18106     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18107     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18108     return R;
18109   }
18110
18111   // If possible, lower this packed shift into a vector multiply instead of
18112   // expanding it into a sequence of scalar shifts.
18113   // Do this only if the vector shift count is a constant build_vector.
18114   if (Op.getOpcode() == ISD::SHL &&
18115       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18116        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18117       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18118     SmallVector<SDValue, 8> Elts;
18119     EVT SVT = VT.getScalarType();
18120     unsigned SVTBits = SVT.getSizeInBits();
18121     const APInt &One = APInt(SVTBits, 1);
18122     unsigned NumElems = VT.getVectorNumElements();
18123
18124     for (unsigned i=0; i !=NumElems; ++i) {
18125       SDValue Op = Amt->getOperand(i);
18126       if (Op->getOpcode() == ISD::UNDEF) {
18127         Elts.push_back(Op);
18128         continue;
18129       }
18130
18131       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18132       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18133       uint64_t ShAmt = C.getZExtValue();
18134       if (ShAmt >= SVTBits) {
18135         Elts.push_back(DAG.getUNDEF(SVT));
18136         continue;
18137       }
18138       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18139     }
18140     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18141     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18142   }
18143
18144   // Lower SHL with variable shift amount.
18145   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18146     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18147
18148     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18149                      DAG.getConstant(0x3f800000U, dl, VT));
18150     Op = DAG.getBitcast(MVT::v4f32, Op);
18151     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18152     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18153   }
18154
18155   // If possible, lower this shift as a sequence of two shifts by
18156   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18157   // Example:
18158   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18159   //
18160   // Could be rewritten as:
18161   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18162   //
18163   // The advantage is that the two shifts from the example would be
18164   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18165   // the vector shift into four scalar shifts plus four pairs of vector
18166   // insert/extract.
18167   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18168       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18169     unsigned TargetOpcode = X86ISD::MOVSS;
18170     bool CanBeSimplified;
18171     // The splat value for the first packed shift (the 'X' from the example).
18172     SDValue Amt1 = Amt->getOperand(0);
18173     // The splat value for the second packed shift (the 'Y' from the example).
18174     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18175                                         Amt->getOperand(2);
18176
18177     // See if it is possible to replace this node with a sequence of
18178     // two shifts followed by a MOVSS/MOVSD
18179     if (VT == MVT::v4i32) {
18180       // Check if it is legal to use a MOVSS.
18181       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18182                         Amt2 == Amt->getOperand(3);
18183       if (!CanBeSimplified) {
18184         // Otherwise, check if we can still simplify this node using a MOVSD.
18185         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18186                           Amt->getOperand(2) == Amt->getOperand(3);
18187         TargetOpcode = X86ISD::MOVSD;
18188         Amt2 = Amt->getOperand(2);
18189       }
18190     } else {
18191       // Do similar checks for the case where the machine value type
18192       // is MVT::v8i16.
18193       CanBeSimplified = Amt1 == Amt->getOperand(1);
18194       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18195         CanBeSimplified = Amt2 == Amt->getOperand(i);
18196
18197       if (!CanBeSimplified) {
18198         TargetOpcode = X86ISD::MOVSD;
18199         CanBeSimplified = true;
18200         Amt2 = Amt->getOperand(4);
18201         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18202           CanBeSimplified = Amt1 == Amt->getOperand(i);
18203         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18204           CanBeSimplified = Amt2 == Amt->getOperand(j);
18205       }
18206     }
18207
18208     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18209         isa<ConstantSDNode>(Amt2)) {
18210       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18211       EVT CastVT = MVT::v4i32;
18212       SDValue Splat1 =
18213         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18214       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18215       SDValue Splat2 =
18216         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18217       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18218       if (TargetOpcode == X86ISD::MOVSD)
18219         CastVT = MVT::v2i64;
18220       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18221       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18222       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18223                                             BitCast1, DAG);
18224       return DAG.getBitcast(VT, Result);
18225     }
18226   }
18227
18228   // v4i32 Non Uniform Shifts.
18229   // If the shift amount is constant we can shift each lane using the SSE2
18230   // immediate shifts, else we need to zero-extend each lane to the lower i64
18231   // and shift using the SSE2 variable shifts.
18232   // The separate results can then be blended together.
18233   if (VT == MVT::v4i32) {
18234     unsigned Opc = Op.getOpcode();
18235     SDValue Amt0, Amt1, Amt2, Amt3;
18236     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18237       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18238       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18239       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18240       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18241     } else {
18242       // ISD::SHL is handled above but we include it here for completeness.
18243       switch (Opc) {
18244       default:
18245         llvm_unreachable("Unknown target vector shift node");
18246       case ISD::SHL:
18247         Opc = X86ISD::VSHL;
18248         break;
18249       case ISD::SRL:
18250         Opc = X86ISD::VSRL;
18251         break;
18252       case ISD::SRA:
18253         Opc = X86ISD::VSRA;
18254         break;
18255       }
18256       // The SSE2 shifts use the lower i64 as the same shift amount for
18257       // all lanes and the upper i64 is ignored. These shuffle masks
18258       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18259       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18260       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18261       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18262       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18263       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18264     }
18265
18266     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18267     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18268     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18269     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18270     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18271     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18272     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18273   }
18274
18275   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18276     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18277     unsigned ShiftOpcode = Op->getOpcode();
18278
18279     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18280       // On SSE41 targets we make use of the fact that VSELECT lowers
18281       // to PBLENDVB which selects bytes based just on the sign bit.
18282       if (Subtarget->hasSSE41()) {
18283         V0 = DAG.getBitcast(VT, V0);
18284         V1 = DAG.getBitcast(VT, V1);
18285         Sel = DAG.getBitcast(VT, Sel);
18286         return DAG.getBitcast(SelVT,
18287                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18288       }
18289       // On pre-SSE41 targets we test for the sign bit by comparing to
18290       // zero - a negative value will set all bits of the lanes to true
18291       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18292       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18293       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18294       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18295     };
18296
18297     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18298     // We can safely do this using i16 shifts as we're only interested in
18299     // the 3 lower bits of each byte.
18300     Amt = DAG.getBitcast(ExtVT, Amt);
18301     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18302     Amt = DAG.getBitcast(VT, Amt);
18303
18304     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18305       // r = VSELECT(r, shift(r, 4), a);
18306       SDValue M =
18307           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18308       R = SignBitSelect(VT, Amt, M, R);
18309
18310       // a += a
18311       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18312
18313       // r = VSELECT(r, shift(r, 2), a);
18314       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18315       R = SignBitSelect(VT, Amt, M, R);
18316
18317       // a += a
18318       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18319
18320       // return VSELECT(r, shift(r, 1), a);
18321       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18322       R = SignBitSelect(VT, Amt, M, R);
18323       return R;
18324     }
18325
18326     if (Op->getOpcode() == ISD::SRA) {
18327       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18328       // so we can correctly sign extend. We don't care what happens to the
18329       // lower byte.
18330       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18331       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18332       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18333       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18334       ALo = DAG.getBitcast(ExtVT, ALo);
18335       AHi = DAG.getBitcast(ExtVT, AHi);
18336       RLo = DAG.getBitcast(ExtVT, RLo);
18337       RHi = DAG.getBitcast(ExtVT, RHi);
18338
18339       // r = VSELECT(r, shift(r, 4), a);
18340       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18341                                 DAG.getConstant(4, dl, ExtVT));
18342       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18343                                 DAG.getConstant(4, dl, ExtVT));
18344       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18345       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18346
18347       // a += a
18348       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18349       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18350
18351       // r = VSELECT(r, shift(r, 2), a);
18352       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18353                         DAG.getConstant(2, dl, ExtVT));
18354       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18355                         DAG.getConstant(2, dl, ExtVT));
18356       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18357       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18358
18359       // a += a
18360       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18361       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18362
18363       // r = VSELECT(r, shift(r, 1), a);
18364       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18365                         DAG.getConstant(1, dl, ExtVT));
18366       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18367                         DAG.getConstant(1, dl, ExtVT));
18368       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18369       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18370
18371       // Logical shift the result back to the lower byte, leaving a zero upper
18372       // byte
18373       // meaning that we can safely pack with PACKUSWB.
18374       RLo =
18375           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18376       RHi =
18377           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18378       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18379     }
18380   }
18381
18382   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18383   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18384   // solution better.
18385   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18386     MVT ExtVT = MVT::v8i32;
18387     unsigned ExtOpc =
18388         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18389     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18390     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18391     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18392                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18393   }
18394
18395   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18396     MVT ExtVT = MVT::v8i32;
18397     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18398     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18399     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18400     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18401     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18402     ALo = DAG.getBitcast(ExtVT, ALo);
18403     AHi = DAG.getBitcast(ExtVT, AHi);
18404     RLo = DAG.getBitcast(ExtVT, RLo);
18405     RHi = DAG.getBitcast(ExtVT, RHi);
18406     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18407     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18408     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18409     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18410     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18411   }
18412
18413   if (VT == MVT::v8i16) {
18414     unsigned ShiftOpcode = Op->getOpcode();
18415
18416     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18417       // On SSE41 targets we make use of the fact that VSELECT lowers
18418       // to PBLENDVB which selects bytes based just on the sign bit.
18419       if (Subtarget->hasSSE41()) {
18420         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18421         V0 = DAG.getBitcast(ExtVT, V0);
18422         V1 = DAG.getBitcast(ExtVT, V1);
18423         Sel = DAG.getBitcast(ExtVT, Sel);
18424         return DAG.getBitcast(
18425             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18426       }
18427       // On pre-SSE41 targets we splat the sign bit - a negative value will
18428       // set all bits of the lanes to true and VSELECT uses that in
18429       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18430       SDValue C =
18431           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18432       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18433     };
18434
18435     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18436     if (Subtarget->hasSSE41()) {
18437       // On SSE41 targets we need to replicate the shift mask in both
18438       // bytes for PBLENDVB.
18439       Amt = DAG.getNode(
18440           ISD::OR, dl, VT,
18441           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18442           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18443     } else {
18444       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18445     }
18446
18447     // r = VSELECT(r, shift(r, 8), a);
18448     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18449     R = SignBitSelect(Amt, M, R);
18450
18451     // a += a
18452     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18453
18454     // r = VSELECT(r, shift(r, 4), a);
18455     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18456     R = SignBitSelect(Amt, M, R);
18457
18458     // a += a
18459     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18460
18461     // r = VSELECT(r, shift(r, 2), a);
18462     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18463     R = SignBitSelect(Amt, M, R);
18464
18465     // a += a
18466     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18467
18468     // return VSELECT(r, shift(r, 1), a);
18469     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18470     R = SignBitSelect(Amt, M, R);
18471     return R;
18472   }
18473
18474   // Decompose 256-bit shifts into smaller 128-bit shifts.
18475   if (VT.is256BitVector()) {
18476     unsigned NumElems = VT.getVectorNumElements();
18477     MVT EltVT = VT.getVectorElementType();
18478     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18479
18480     // Extract the two vectors
18481     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18482     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18483
18484     // Recreate the shift amount vectors
18485     SDValue Amt1, Amt2;
18486     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18487       // Constant shift amount
18488       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18489       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18490       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18491
18492       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18493       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18494     } else {
18495       // Variable shift amount
18496       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18497       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18498     }
18499
18500     // Issue new vector shifts for the smaller types
18501     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18502     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18503
18504     // Concatenate the result back
18505     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18506   }
18507
18508   return SDValue();
18509 }
18510
18511 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18512   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18513   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18514   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18515   // has only one use.
18516   SDNode *N = Op.getNode();
18517   SDValue LHS = N->getOperand(0);
18518   SDValue RHS = N->getOperand(1);
18519   unsigned BaseOp = 0;
18520   unsigned Cond = 0;
18521   SDLoc DL(Op);
18522   switch (Op.getOpcode()) {
18523   default: llvm_unreachable("Unknown ovf instruction!");
18524   case ISD::SADDO:
18525     // A subtract of one will be selected as a INC. Note that INC doesn't
18526     // set CF, so we can't do this for UADDO.
18527     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18528       if (C->isOne()) {
18529         BaseOp = X86ISD::INC;
18530         Cond = X86::COND_O;
18531         break;
18532       }
18533     BaseOp = X86ISD::ADD;
18534     Cond = X86::COND_O;
18535     break;
18536   case ISD::UADDO:
18537     BaseOp = X86ISD::ADD;
18538     Cond = X86::COND_B;
18539     break;
18540   case ISD::SSUBO:
18541     // A subtract of one will be selected as a DEC. Note that DEC doesn't
18542     // set CF, so we can't do this for USUBO.
18543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18544       if (C->isOne()) {
18545         BaseOp = X86ISD::DEC;
18546         Cond = X86::COND_O;
18547         break;
18548       }
18549     BaseOp = X86ISD::SUB;
18550     Cond = X86::COND_O;
18551     break;
18552   case ISD::USUBO:
18553     BaseOp = X86ISD::SUB;
18554     Cond = X86::COND_B;
18555     break;
18556   case ISD::SMULO:
18557     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18558     Cond = X86::COND_O;
18559     break;
18560   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18561     if (N->getValueType(0) == MVT::i8) {
18562       BaseOp = X86ISD::UMUL8;
18563       Cond = X86::COND_O;
18564       break;
18565     }
18566     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18567                                  MVT::i32);
18568     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18569
18570     SDValue SetCC =
18571       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18572                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
18573                   SDValue(Sum.getNode(), 2));
18574
18575     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18576   }
18577   }
18578
18579   // Also sets EFLAGS.
18580   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18581   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18582
18583   SDValue SetCC =
18584     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18585                 DAG.getConstant(Cond, DL, MVT::i32),
18586                 SDValue(Sum.getNode(), 1));
18587
18588   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18589 }
18590
18591 /// Returns true if the operand type is exactly twice the native width, and
18592 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18593 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18594 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18595 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18596   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18597
18598   if (OpWidth == 64)
18599     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18600   else if (OpWidth == 128)
18601     return Subtarget->hasCmpxchg16b();
18602   else
18603     return false;
18604 }
18605
18606 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18607   return needsCmpXchgNb(SI->getValueOperand()->getType());
18608 }
18609
18610 // Note: this turns large loads into lock cmpxchg8b/16b.
18611 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18612 TargetLowering::AtomicExpansionKind
18613 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18614   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18615   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18616                                                : AtomicExpansionKind::None;
18617 }
18618
18619 TargetLowering::AtomicExpansionKind
18620 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18621   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18622   Type *MemType = AI->getType();
18623
18624   // If the operand is too big, we must see if cmpxchg8/16b is available
18625   // and default to library calls otherwise.
18626   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18627     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18628                                    : AtomicExpansionKind::None;
18629   }
18630
18631   AtomicRMWInst::BinOp Op = AI->getOperation();
18632   switch (Op) {
18633   default:
18634     llvm_unreachable("Unknown atomic operation");
18635   case AtomicRMWInst::Xchg:
18636   case AtomicRMWInst::Add:
18637   case AtomicRMWInst::Sub:
18638     // It's better to use xadd, xsub or xchg for these in all cases.
18639     return AtomicExpansionKind::None;
18640   case AtomicRMWInst::Or:
18641   case AtomicRMWInst::And:
18642   case AtomicRMWInst::Xor:
18643     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18644     // prefix to a normal instruction for these operations.
18645     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18646                             : AtomicExpansionKind::None;
18647   case AtomicRMWInst::Nand:
18648   case AtomicRMWInst::Max:
18649   case AtomicRMWInst::Min:
18650   case AtomicRMWInst::UMax:
18651   case AtomicRMWInst::UMin:
18652     // These always require a non-trivial set of data operations on x86. We must
18653     // use a cmpxchg loop.
18654     return AtomicExpansionKind::CmpXChg;
18655   }
18656 }
18657
18658 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18659   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18660   // no-sse2). There isn't any reason to disable it if the target processor
18661   // supports it.
18662   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18663 }
18664
18665 LoadInst *
18666 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18667   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18668   Type *MemType = AI->getType();
18669   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18670   // there is no benefit in turning such RMWs into loads, and it is actually
18671   // harmful as it introduces a mfence.
18672   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18673     return nullptr;
18674
18675   auto Builder = IRBuilder<>(AI);
18676   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18677   auto SynchScope = AI->getSynchScope();
18678   // We must restrict the ordering to avoid generating loads with Release or
18679   // ReleaseAcquire orderings.
18680   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18681   auto Ptr = AI->getPointerOperand();
18682
18683   // Before the load we need a fence. Here is an example lifted from
18684   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18685   // is required:
18686   // Thread 0:
18687   //   x.store(1, relaxed);
18688   //   r1 = y.fetch_add(0, release);
18689   // Thread 1:
18690   //   y.fetch_add(42, acquire);
18691   //   r2 = x.load(relaxed);
18692   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18693   // lowered to just a load without a fence. A mfence flushes the store buffer,
18694   // making the optimization clearly correct.
18695   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18696   // otherwise, we might be able to be more aggressive on relaxed idempotent
18697   // rmw. In practice, they do not look useful, so we don't try to be
18698   // especially clever.
18699   if (SynchScope == SingleThread)
18700     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18701     // the IR level, so we must wrap it in an intrinsic.
18702     return nullptr;
18703
18704   if (!hasMFENCE(*Subtarget))
18705     // FIXME: it might make sense to use a locked operation here but on a
18706     // different cache-line to prevent cache-line bouncing. In practice it
18707     // is probably a small win, and x86 processors without mfence are rare
18708     // enough that we do not bother.
18709     return nullptr;
18710
18711   Function *MFence =
18712       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18713   Builder.CreateCall(MFence, {});
18714
18715   // Finally we can emit the atomic load.
18716   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18717           AI->getType()->getPrimitiveSizeInBits());
18718   Loaded->setAtomic(Order, SynchScope);
18719   AI->replaceAllUsesWith(Loaded);
18720   AI->eraseFromParent();
18721   return Loaded;
18722 }
18723
18724 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18725                                  SelectionDAG &DAG) {
18726   SDLoc dl(Op);
18727   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18728     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18729   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18730     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18731
18732   // The only fence that needs an instruction is a sequentially-consistent
18733   // cross-thread fence.
18734   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18735     if (hasMFENCE(*Subtarget))
18736       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18737
18738     SDValue Chain = Op.getOperand(0);
18739     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18740     SDValue Ops[] = {
18741       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18742       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18743       DAG.getRegister(0, MVT::i32),            // Index
18744       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18745       DAG.getRegister(0, MVT::i32),            // Segment.
18746       Zero,
18747       Chain
18748     };
18749     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18750     return SDValue(Res, 0);
18751   }
18752
18753   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18754   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18755 }
18756
18757 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18758                              SelectionDAG &DAG) {
18759   MVT T = Op.getSimpleValueType();
18760   SDLoc DL(Op);
18761   unsigned Reg = 0;
18762   unsigned size = 0;
18763   switch(T.SimpleTy) {
18764   default: llvm_unreachable("Invalid value type!");
18765   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18766   case MVT::i16: Reg = X86::AX;  size = 2; break;
18767   case MVT::i32: Reg = X86::EAX; size = 4; break;
18768   case MVT::i64:
18769     assert(Subtarget->is64Bit() && "Node not type legal!");
18770     Reg = X86::RAX; size = 8;
18771     break;
18772   }
18773   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18774                                   Op.getOperand(2), SDValue());
18775   SDValue Ops[] = { cpIn.getValue(0),
18776                     Op.getOperand(1),
18777                     Op.getOperand(3),
18778                     DAG.getTargetConstant(size, DL, MVT::i8),
18779                     cpIn.getValue(1) };
18780   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18781   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18782   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18783                                            Ops, T, MMO);
18784
18785   SDValue cpOut =
18786     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18787   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18788                                       MVT::i32, cpOut.getValue(2));
18789   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18790                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18791                                 EFLAGS);
18792
18793   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18794   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18795   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18796   return SDValue();
18797 }
18798
18799 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18800                             SelectionDAG &DAG) {
18801   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18802   MVT DstVT = Op.getSimpleValueType();
18803
18804   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18805     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18806     if (DstVT != MVT::f64)
18807       // This conversion needs to be expanded.
18808       return SDValue();
18809
18810     SDValue InVec = Op->getOperand(0);
18811     SDLoc dl(Op);
18812     unsigned NumElts = SrcVT.getVectorNumElements();
18813     EVT SVT = SrcVT.getVectorElementType();
18814
18815     // Widen the vector in input in the case of MVT::v2i32.
18816     // Example: from MVT::v2i32 to MVT::v4i32.
18817     SmallVector<SDValue, 16> Elts;
18818     for (unsigned i = 0, e = NumElts; i != e; ++i)
18819       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18820                                  DAG.getIntPtrConstant(i, dl)));
18821
18822     // Explicitly mark the extra elements as Undef.
18823     Elts.append(NumElts, DAG.getUNDEF(SVT));
18824
18825     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18826     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18827     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18828     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18829                        DAG.getIntPtrConstant(0, dl));
18830   }
18831
18832   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18833          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18834   assert((DstVT == MVT::i64 ||
18835           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18836          "Unexpected custom BITCAST");
18837   // i64 <=> MMX conversions are Legal.
18838   if (SrcVT==MVT::i64 && DstVT.isVector())
18839     return Op;
18840   if (DstVT==MVT::i64 && SrcVT.isVector())
18841     return Op;
18842   // MMX <=> MMX conversions are Legal.
18843   if (SrcVT.isVector() && DstVT.isVector())
18844     return Op;
18845   // All other conversions need to be expanded.
18846   return SDValue();
18847 }
18848
18849 /// Compute the horizontal sum of bytes in V for the elements of VT.
18850 ///
18851 /// Requires V to be a byte vector and VT to be an integer vector type with
18852 /// wider elements than V's type. The width of the elements of VT determines
18853 /// how many bytes of V are summed horizontally to produce each element of the
18854 /// result.
18855 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18856                                       const X86Subtarget *Subtarget,
18857                                       SelectionDAG &DAG) {
18858   SDLoc DL(V);
18859   MVT ByteVecVT = V.getSimpleValueType();
18860   MVT EltVT = VT.getVectorElementType();
18861   int NumElts = VT.getVectorNumElements();
18862   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18863          "Expected value to have byte element type.");
18864   assert(EltVT != MVT::i8 &&
18865          "Horizontal byte sum only makes sense for wider elements!");
18866   unsigned VecSize = VT.getSizeInBits();
18867   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18868
18869   // PSADBW instruction horizontally add all bytes and leave the result in i64
18870   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18871   if (EltVT == MVT::i64) {
18872     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18873     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18874     return DAG.getBitcast(VT, V);
18875   }
18876
18877   if (EltVT == MVT::i32) {
18878     // We unpack the low half and high half into i32s interleaved with zeros so
18879     // that we can use PSADBW to horizontally sum them. The most useful part of
18880     // this is that it lines up the results of two PSADBW instructions to be
18881     // two v2i64 vectors which concatenated are the 4 population counts. We can
18882     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18883     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18884     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18885     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18886
18887     // Do the horizontal sums into two v2i64s.
18888     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18889     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18890                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18891     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18892                        DAG.getBitcast(ByteVecVT, High), Zeros);
18893
18894     // Merge them together.
18895     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18896     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18897                     DAG.getBitcast(ShortVecVT, Low),
18898                     DAG.getBitcast(ShortVecVT, High));
18899
18900     return DAG.getBitcast(VT, V);
18901   }
18902
18903   // The only element type left is i16.
18904   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18905
18906   // To obtain pop count for each i16 element starting from the pop count for
18907   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18908   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18909   // directly supported.
18910   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18911   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18912   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18913   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18914                   DAG.getBitcast(ByteVecVT, V));
18915   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18916 }
18917
18918 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18919                                         const X86Subtarget *Subtarget,
18920                                         SelectionDAG &DAG) {
18921   MVT VT = Op.getSimpleValueType();
18922   MVT EltVT = VT.getVectorElementType();
18923   unsigned VecSize = VT.getSizeInBits();
18924
18925   // Implement a lookup table in register by using an algorithm based on:
18926   // http://wm.ite.pl/articles/sse-popcount.html
18927   //
18928   // The general idea is that every lower byte nibble in the input vector is an
18929   // index into a in-register pre-computed pop count table. We then split up the
18930   // input vector in two new ones: (1) a vector with only the shifted-right
18931   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18932   // masked out higher ones) for each byte. PSHUB is used separately with both
18933   // to index the in-register table. Next, both are added and the result is a
18934   // i8 vector where each element contains the pop count for input byte.
18935   //
18936   // To obtain the pop count for elements != i8, we follow up with the same
18937   // approach and use additional tricks as described below.
18938   //
18939   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18940                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18941                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18942                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18943
18944   int NumByteElts = VecSize / 8;
18945   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18946   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18947   SmallVector<SDValue, 16> LUTVec;
18948   for (int i = 0; i < NumByteElts; ++i)
18949     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18950   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18951   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18952                                   DAG.getConstant(0x0F, DL, MVT::i8));
18953   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18954
18955   // High nibbles
18956   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18957   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18958   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18959
18960   // Low nibbles
18961   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18962
18963   // The input vector is used as the shuffle mask that index elements into the
18964   // LUT. After counting low and high nibbles, add the vector to obtain the
18965   // final pop count per i8 element.
18966   SDValue HighPopCnt =
18967       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18968   SDValue LowPopCnt =
18969       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18970   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18971
18972   if (EltVT == MVT::i8)
18973     return PopCnt;
18974
18975   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18976 }
18977
18978 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18979                                        const X86Subtarget *Subtarget,
18980                                        SelectionDAG &DAG) {
18981   MVT VT = Op.getSimpleValueType();
18982   assert(VT.is128BitVector() &&
18983          "Only 128-bit vector bitmath lowering supported.");
18984
18985   int VecSize = VT.getSizeInBits();
18986   MVT EltVT = VT.getVectorElementType();
18987   int Len = EltVT.getSizeInBits();
18988
18989   // This is the vectorized version of the "best" algorithm from
18990   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18991   // with a minor tweak to use a series of adds + shifts instead of vector
18992   // multiplications. Implemented for all integer vector types. We only use
18993   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18994   // much faster, even faster than using native popcnt instructions.
18995
18996   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18997     MVT VT = V.getSimpleValueType();
18998     SmallVector<SDValue, 32> Shifters(
18999         VT.getVectorNumElements(),
19000         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19001     return DAG.getNode(OpCode, DL, VT, V,
19002                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19003   };
19004   auto GetMask = [&](SDValue V, APInt Mask) {
19005     MVT VT = V.getSimpleValueType();
19006     SmallVector<SDValue, 32> Masks(
19007         VT.getVectorNumElements(),
19008         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19009     return DAG.getNode(ISD::AND, DL, VT, V,
19010                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19011   };
19012
19013   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19014   // x86, so set the SRL type to have elements at least i16 wide. This is
19015   // correct because all of our SRLs are followed immediately by a mask anyways
19016   // that handles any bits that sneak into the high bits of the byte elements.
19017   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19018
19019   SDValue V = Op;
19020
19021   // v = v - ((v >> 1) & 0x55555555...)
19022   SDValue Srl =
19023       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19024   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19025   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19026
19027   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19028   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19029   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19030   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19031   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19032
19033   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19034   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19035   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19036   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19037
19038   // At this point, V contains the byte-wise population count, and we are
19039   // merely doing a horizontal sum if necessary to get the wider element
19040   // counts.
19041   if (EltVT == MVT::i8)
19042     return V;
19043
19044   return LowerHorizontalByteSum(
19045       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19046       DAG);
19047 }
19048
19049 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19050                                 SelectionDAG &DAG) {
19051   MVT VT = Op.getSimpleValueType();
19052   // FIXME: Need to add AVX-512 support here!
19053   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19054          "Unknown CTPOP type to handle");
19055   SDLoc DL(Op.getNode());
19056   SDValue Op0 = Op.getOperand(0);
19057
19058   if (!Subtarget->hasSSSE3()) {
19059     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19060     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19061     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19062   }
19063
19064   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19065     unsigned NumElems = VT.getVectorNumElements();
19066
19067     // Extract each 128-bit vector, compute pop count and concat the result.
19068     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19069     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19070
19071     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19072                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19073                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19074   }
19075
19076   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19077 }
19078
19079 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19080                           SelectionDAG &DAG) {
19081   assert(Op.getValueType().isVector() &&
19082          "We only do custom lowering for vector population count.");
19083   return LowerVectorCTPOP(Op, Subtarget, DAG);
19084 }
19085
19086 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19087   SDNode *Node = Op.getNode();
19088   SDLoc dl(Node);
19089   EVT T = Node->getValueType(0);
19090   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19091                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19092   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19093                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19094                        Node->getOperand(0),
19095                        Node->getOperand(1), negOp,
19096                        cast<AtomicSDNode>(Node)->getMemOperand(),
19097                        cast<AtomicSDNode>(Node)->getOrdering(),
19098                        cast<AtomicSDNode>(Node)->getSynchScope());
19099 }
19100
19101 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19102   SDNode *Node = Op.getNode();
19103   SDLoc dl(Node);
19104   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19105
19106   // Convert seq_cst store -> xchg
19107   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19108   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19109   //        (The only way to get a 16-byte store is cmpxchg16b)
19110   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19111   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19112       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19113     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19114                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19115                                  Node->getOperand(0),
19116                                  Node->getOperand(1), Node->getOperand(2),
19117                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19118                                  cast<AtomicSDNode>(Node)->getOrdering(),
19119                                  cast<AtomicSDNode>(Node)->getSynchScope());
19120     return Swap.getValue(1);
19121   }
19122   // Other atomic stores have a simple pattern.
19123   return Op;
19124 }
19125
19126 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19127   EVT VT = Op.getNode()->getSimpleValueType(0);
19128
19129   // Let legalize expand this if it isn't a legal type yet.
19130   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19131     return SDValue();
19132
19133   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19134
19135   unsigned Opc;
19136   bool ExtraOp = false;
19137   switch (Op.getOpcode()) {
19138   default: llvm_unreachable("Invalid code");
19139   case ISD::ADDC: Opc = X86ISD::ADD; break;
19140   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19141   case ISD::SUBC: Opc = X86ISD::SUB; break;
19142   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19143   }
19144
19145   if (!ExtraOp)
19146     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19147                        Op.getOperand(1));
19148   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19149                      Op.getOperand(1), Op.getOperand(2));
19150 }
19151
19152 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19153                             SelectionDAG &DAG) {
19154   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19155
19156   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19157   // which returns the values as { float, float } (in XMM0) or
19158   // { double, double } (which is returned in XMM0, XMM1).
19159   SDLoc dl(Op);
19160   SDValue Arg = Op.getOperand(0);
19161   EVT ArgVT = Arg.getValueType();
19162   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19163
19164   TargetLowering::ArgListTy Args;
19165   TargetLowering::ArgListEntry Entry;
19166
19167   Entry.Node = Arg;
19168   Entry.Ty = ArgTy;
19169   Entry.isSExt = false;
19170   Entry.isZExt = false;
19171   Args.push_back(Entry);
19172
19173   bool isF64 = ArgVT == MVT::f64;
19174   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19175   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19176   // the results are returned via SRet in memory.
19177   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19179   SDValue Callee =
19180       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19181
19182   Type *RetTy = isF64
19183     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19184     : (Type*)VectorType::get(ArgTy, 4);
19185
19186   TargetLowering::CallLoweringInfo CLI(DAG);
19187   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19188     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19189
19190   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19191
19192   if (isF64)
19193     // Returned in xmm0 and xmm1.
19194     return CallResult.first;
19195
19196   // Returned in bits 0:31 and 32:64 xmm0.
19197   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19198                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19199   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19200                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19201   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19202   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19203 }
19204
19205 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19206                              SelectionDAG &DAG) {
19207   assert(Subtarget->hasAVX512() &&
19208          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19209
19210   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19211   EVT VT = N->getValue().getValueType();
19212   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19213   SDLoc dl(Op);
19214
19215   // X86 scatter kills mask register, so its type should be added to
19216   // the list of return values
19217   if (N->getNumValues() == 1) {
19218     SDValue Index = N->getIndex();
19219     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19220         !Index.getValueType().is512BitVector())
19221       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19222
19223     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19224     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19225                       N->getOperand(3), Index };
19226
19227     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19228     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19229     return SDValue(NewScatter.getNode(), 0);
19230   }
19231   return Op;
19232 }
19233
19234 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19235                             SelectionDAG &DAG) {
19236   assert(Subtarget->hasAVX512() &&
19237          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19238
19239   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19240   EVT VT = Op.getValueType();
19241   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19242   SDLoc dl(Op);
19243
19244   SDValue Index = N->getIndex();
19245   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19246       !Index.getValueType().is512BitVector()) {
19247     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19248     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19249                       N->getOperand(3), Index };
19250     DAG.UpdateNodeOperands(N, Ops);
19251   }
19252   return Op;
19253 }
19254
19255 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19256                                                     SelectionDAG &DAG) const {
19257   // TODO: Eventually, the lowering of these nodes should be informed by or
19258   // deferred to the GC strategy for the function in which they appear. For
19259   // now, however, they must be lowered to something. Since they are logically
19260   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19261   // require special handling for these nodes), lower them as literal NOOPs for
19262   // the time being.
19263   SmallVector<SDValue, 2> Ops;
19264
19265   Ops.push_back(Op.getOperand(0));
19266   if (Op->getGluedNode())
19267     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19268
19269   SDLoc OpDL(Op);
19270   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19271   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19272
19273   return NOOP;
19274 }
19275
19276 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19277                                                   SelectionDAG &DAG) const {
19278   // TODO: Eventually, the lowering of these nodes should be informed by or
19279   // deferred to the GC strategy for the function in which they appear. For
19280   // now, however, they must be lowered to something. Since they are logically
19281   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19282   // require special handling for these nodes), lower them as literal NOOPs for
19283   // the time being.
19284   SmallVector<SDValue, 2> Ops;
19285
19286   Ops.push_back(Op.getOperand(0));
19287   if (Op->getGluedNode())
19288     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19289
19290   SDLoc OpDL(Op);
19291   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19292   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19293
19294   return NOOP;
19295 }
19296
19297 /// LowerOperation - Provide custom lowering hooks for some operations.
19298 ///
19299 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19300   switch (Op.getOpcode()) {
19301   default: llvm_unreachable("Should not custom lower this!");
19302   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19303   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19304     return LowerCMP_SWAP(Op, Subtarget, DAG);
19305   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19306   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19307   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19308   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19309   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19310   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19311   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19312   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19313   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19314   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19315   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19316   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19317   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19318   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19319   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19320   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19321   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19322   case ISD::SHL_PARTS:
19323   case ISD::SRA_PARTS:
19324   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19325   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19326   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19327   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19328   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19329   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19330   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19331   case ISD::SIGN_EXTEND_VECTOR_INREG:
19332     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19333   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19334   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19335   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19336   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19337   case ISD::FABS:
19338   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19339   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19340   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19341   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19342   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19343   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19344   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19345   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19346   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19347   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19348   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19349   case ISD::INTRINSIC_VOID:
19350   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19351   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19352   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19353   case ISD::FRAME_TO_ARGS_OFFSET:
19354                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19355   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19356   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19357   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19358   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19359   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19360   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19361   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19362   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
19363   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19364   case ISD::CTTZ:
19365   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19366   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19367   case ISD::UMUL_LOHI:
19368   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19369   case ISD::SRA:
19370   case ISD::SRL:
19371   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19372   case ISD::SADDO:
19373   case ISD::UADDO:
19374   case ISD::SSUBO:
19375   case ISD::USUBO:
19376   case ISD::SMULO:
19377   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19378   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19379   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19380   case ISD::ADDC:
19381   case ISD::ADDE:
19382   case ISD::SUBC:
19383   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19384   case ISD::ADD:                return LowerADD(Op, DAG);
19385   case ISD::SUB:                return LowerSUB(Op, DAG);
19386   case ISD::SMAX:
19387   case ISD::SMIN:
19388   case ISD::UMAX:
19389   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19390   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19391   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19392   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19393   case ISD::GC_TRANSITION_START:
19394                                 return LowerGC_TRANSITION_START(Op, DAG);
19395   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19396   }
19397 }
19398
19399 /// ReplaceNodeResults - Replace a node with an illegal result type
19400 /// with a new node built out of custom code.
19401 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19402                                            SmallVectorImpl<SDValue>&Results,
19403                                            SelectionDAG &DAG) const {
19404   SDLoc dl(N);
19405   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19406   switch (N->getOpcode()) {
19407   default:
19408     llvm_unreachable("Do not know how to custom type legalize this operation!");
19409   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19410   case X86ISD::FMINC:
19411   case X86ISD::FMIN:
19412   case X86ISD::FMAXC:
19413   case X86ISD::FMAX: {
19414     EVT VT = N->getValueType(0);
19415     if (VT != MVT::v2f32)
19416       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19417     SDValue UNDEF = DAG.getUNDEF(VT);
19418     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19419                               N->getOperand(0), UNDEF);
19420     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19421                               N->getOperand(1), UNDEF);
19422     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19423     return;
19424   }
19425   case ISD::SIGN_EXTEND_INREG:
19426   case ISD::ADDC:
19427   case ISD::ADDE:
19428   case ISD::SUBC:
19429   case ISD::SUBE:
19430     // We don't want to expand or promote these.
19431     return;
19432   case ISD::SDIV:
19433   case ISD::UDIV:
19434   case ISD::SREM:
19435   case ISD::UREM:
19436   case ISD::SDIVREM:
19437   case ISD::UDIVREM: {
19438     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19439     Results.push_back(V);
19440     return;
19441   }
19442   case ISD::FP_TO_SINT:
19443   case ISD::FP_TO_UINT: {
19444     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19445
19446     std::pair<SDValue,SDValue> Vals =
19447         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19448     SDValue FIST = Vals.first, StackSlot = Vals.second;
19449     if (FIST.getNode()) {
19450       EVT VT = N->getValueType(0);
19451       // Return a load from the stack slot.
19452       if (StackSlot.getNode())
19453         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19454                                       MachinePointerInfo(),
19455                                       false, false, false, 0));
19456       else
19457         Results.push_back(FIST);
19458     }
19459     return;
19460   }
19461   case ISD::UINT_TO_FP: {
19462     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19463     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19464         N->getValueType(0) != MVT::v2f32)
19465       return;
19466     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19467                                  N->getOperand(0));
19468     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19469                                      MVT::f64);
19470     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19471     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19472                              DAG.getBitcast(MVT::v2i64, VBias));
19473     Or = DAG.getBitcast(MVT::v2f64, Or);
19474     // TODO: Are there any fast-math-flags to propagate here?
19475     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19476     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19477     return;
19478   }
19479   case ISD::FP_ROUND: {
19480     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19481         return;
19482     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19483     Results.push_back(V);
19484     return;
19485   }
19486   case ISD::FP_EXTEND: {
19487     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19488     // No other ValueType for FP_EXTEND should reach this point.
19489     assert(N->getValueType(0) == MVT::v2f32 &&
19490            "Do not know how to legalize this Node");
19491     return;
19492   }
19493   case ISD::INTRINSIC_W_CHAIN: {
19494     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19495     switch (IntNo) {
19496     default : llvm_unreachable("Do not know how to custom type "
19497                                "legalize this intrinsic operation!");
19498     case Intrinsic::x86_rdtsc:
19499       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19500                                      Results);
19501     case Intrinsic::x86_rdtscp:
19502       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19503                                      Results);
19504     case Intrinsic::x86_rdpmc:
19505       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19506     }
19507   }
19508   case ISD::READCYCLECOUNTER: {
19509     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19510                                    Results);
19511   }
19512   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19513     EVT T = N->getValueType(0);
19514     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19515     bool Regs64bit = T == MVT::i128;
19516     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19517     SDValue cpInL, cpInH;
19518     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19519                         DAG.getConstant(0, dl, HalfT));
19520     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19521                         DAG.getConstant(1, dl, HalfT));
19522     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19523                              Regs64bit ? X86::RAX : X86::EAX,
19524                              cpInL, SDValue());
19525     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19526                              Regs64bit ? X86::RDX : X86::EDX,
19527                              cpInH, cpInL.getValue(1));
19528     SDValue swapInL, swapInH;
19529     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19530                           DAG.getConstant(0, dl, HalfT));
19531     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19532                           DAG.getConstant(1, dl, HalfT));
19533     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19534                                Regs64bit ? X86::RBX : X86::EBX,
19535                                swapInL, cpInH.getValue(1));
19536     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19537                                Regs64bit ? X86::RCX : X86::ECX,
19538                                swapInH, swapInL.getValue(1));
19539     SDValue Ops[] = { swapInH.getValue(0),
19540                       N->getOperand(1),
19541                       swapInH.getValue(1) };
19542     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19543     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19544     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19545                                   X86ISD::LCMPXCHG8_DAG;
19546     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19547     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19548                                         Regs64bit ? X86::RAX : X86::EAX,
19549                                         HalfT, Result.getValue(1));
19550     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19551                                         Regs64bit ? X86::RDX : X86::EDX,
19552                                         HalfT, cpOutL.getValue(2));
19553     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19554
19555     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19556                                         MVT::i32, cpOutH.getValue(2));
19557     SDValue Success =
19558         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19559                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19560     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19561
19562     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19563     Results.push_back(Success);
19564     Results.push_back(EFLAGS.getValue(1));
19565     return;
19566   }
19567   case ISD::ATOMIC_SWAP:
19568   case ISD::ATOMIC_LOAD_ADD:
19569   case ISD::ATOMIC_LOAD_SUB:
19570   case ISD::ATOMIC_LOAD_AND:
19571   case ISD::ATOMIC_LOAD_OR:
19572   case ISD::ATOMIC_LOAD_XOR:
19573   case ISD::ATOMIC_LOAD_NAND:
19574   case ISD::ATOMIC_LOAD_MIN:
19575   case ISD::ATOMIC_LOAD_MAX:
19576   case ISD::ATOMIC_LOAD_UMIN:
19577   case ISD::ATOMIC_LOAD_UMAX:
19578   case ISD::ATOMIC_LOAD: {
19579     // Delegate to generic TypeLegalization. Situations we can really handle
19580     // should have already been dealt with by AtomicExpandPass.cpp.
19581     break;
19582   }
19583   case ISD::BITCAST: {
19584     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19585     EVT DstVT = N->getValueType(0);
19586     EVT SrcVT = N->getOperand(0)->getValueType(0);
19587
19588     if (SrcVT != MVT::f64 ||
19589         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19590       return;
19591
19592     unsigned NumElts = DstVT.getVectorNumElements();
19593     EVT SVT = DstVT.getVectorElementType();
19594     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19595     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19596                                    MVT::v2f64, N->getOperand(0));
19597     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19598
19599     if (ExperimentalVectorWideningLegalization) {
19600       // If we are legalizing vectors by widening, we already have the desired
19601       // legal vector type, just return it.
19602       Results.push_back(ToVecInt);
19603       return;
19604     }
19605
19606     SmallVector<SDValue, 8> Elts;
19607     for (unsigned i = 0, e = NumElts; i != e; ++i)
19608       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19609                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19610
19611     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19612   }
19613   }
19614 }
19615
19616 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19617   switch ((X86ISD::NodeType)Opcode) {
19618   case X86ISD::FIRST_NUMBER:       break;
19619   case X86ISD::BSF:                return "X86ISD::BSF";
19620   case X86ISD::BSR:                return "X86ISD::BSR";
19621   case X86ISD::SHLD:               return "X86ISD::SHLD";
19622   case X86ISD::SHRD:               return "X86ISD::SHRD";
19623   case X86ISD::FAND:               return "X86ISD::FAND";
19624   case X86ISD::FANDN:              return "X86ISD::FANDN";
19625   case X86ISD::FOR:                return "X86ISD::FOR";
19626   case X86ISD::FXOR:               return "X86ISD::FXOR";
19627   case X86ISD::FILD:               return "X86ISD::FILD";
19628   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19629   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19630   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19631   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19632   case X86ISD::FLD:                return "X86ISD::FLD";
19633   case X86ISD::FST:                return "X86ISD::FST";
19634   case X86ISD::CALL:               return "X86ISD::CALL";
19635   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19636   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19637   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19638   case X86ISD::BT:                 return "X86ISD::BT";
19639   case X86ISD::CMP:                return "X86ISD::CMP";
19640   case X86ISD::COMI:               return "X86ISD::COMI";
19641   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19642   case X86ISD::CMPM:               return "X86ISD::CMPM";
19643   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19644   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19645   case X86ISD::SETCC:              return "X86ISD::SETCC";
19646   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19647   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19648   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19649   case X86ISD::CMOV:               return "X86ISD::CMOV";
19650   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19651   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19652   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19653   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19654   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19655   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19656   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19657   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19658   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19659   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19660   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19661   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19662   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19663   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19664   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19665   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19666   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19667   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19668   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19669   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19670   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19671   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19672   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19673   case X86ISD::HADD:               return "X86ISD::HADD";
19674   case X86ISD::HSUB:               return "X86ISD::HSUB";
19675   case X86ISD::FHADD:              return "X86ISD::FHADD";
19676   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19677   case X86ISD::ABS:                return "X86ISD::ABS";
19678   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
19679   case X86ISD::FMAX:               return "X86ISD::FMAX";
19680   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19681   case X86ISD::FMIN:               return "X86ISD::FMIN";
19682   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19683   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19684   case X86ISD::FMINC:              return "X86ISD::FMINC";
19685   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19686   case X86ISD::FRCP:               return "X86ISD::FRCP";
19687   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19688   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19689   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19690   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19691   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19692   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19693   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19694   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19695   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19696   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19697   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19698   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19699   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19700   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19701   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19702   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19703   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19704   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19705   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19706   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19707   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19708   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19709   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19710   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19711   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19712   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19713   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19714   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19715   case X86ISD::VSHL:               return "X86ISD::VSHL";
19716   case X86ISD::VSRL:               return "X86ISD::VSRL";
19717   case X86ISD::VSRA:               return "X86ISD::VSRA";
19718   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19719   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19720   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19721   case X86ISD::CMPP:               return "X86ISD::CMPP";
19722   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19723   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19724   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19725   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19726   case X86ISD::ADD:                return "X86ISD::ADD";
19727   case X86ISD::SUB:                return "X86ISD::SUB";
19728   case X86ISD::ADC:                return "X86ISD::ADC";
19729   case X86ISD::SBB:                return "X86ISD::SBB";
19730   case X86ISD::SMUL:               return "X86ISD::SMUL";
19731   case X86ISD::UMUL:               return "X86ISD::UMUL";
19732   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19733   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19734   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19735   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19736   case X86ISD::INC:                return "X86ISD::INC";
19737   case X86ISD::DEC:                return "X86ISD::DEC";
19738   case X86ISD::OR:                 return "X86ISD::OR";
19739   case X86ISD::XOR:                return "X86ISD::XOR";
19740   case X86ISD::AND:                return "X86ISD::AND";
19741   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19742   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19743   case X86ISD::PTEST:              return "X86ISD::PTEST";
19744   case X86ISD::TESTP:              return "X86ISD::TESTP";
19745   case X86ISD::TESTM:              return "X86ISD::TESTM";
19746   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19747   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19748   case X86ISD::KTEST:              return "X86ISD::KTEST";
19749   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19750   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19751   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19752   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19753   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19754   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19755   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19756   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19757   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19758   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19759   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19760   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19761   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19762   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19763   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19764   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19765   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19766   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19767   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19768   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19769   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19770   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19771   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19772   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19773   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19774   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19775   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19776   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19777   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19778   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19779   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19780   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19781   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19782   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19783   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19784   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19785   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
19786   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19787   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19788   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19789   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19790   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19791   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19792   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19793   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19794   case X86ISD::SAHF:               return "X86ISD::SAHF";
19795   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19796   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19797   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19798   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19799   case X86ISD::FMADD:              return "X86ISD::FMADD";
19800   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19801   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19802   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19803   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19804   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19805   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19806   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19807   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19808   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19809   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19810   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19811   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19812   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19813   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
19814   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19815   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19816   case X86ISD::XTEST:              return "X86ISD::XTEST";
19817   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19818   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19819   case X86ISD::SELECT:             return "X86ISD::SELECT";
19820   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19821   case X86ISD::RCP28:              return "X86ISD::RCP28";
19822   case X86ISD::EXP2:               return "X86ISD::EXP2";
19823   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19824   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19825   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19826   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19827   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19828   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19829   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19830   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19831   case X86ISD::ADDS:               return "X86ISD::ADDS";
19832   case X86ISD::SUBS:               return "X86ISD::SUBS";
19833   case X86ISD::AVG:                return "X86ISD::AVG";
19834   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19835   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19836   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19837   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19838   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19839   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
19840   }
19841   return nullptr;
19842 }
19843
19844 // isLegalAddressingMode - Return true if the addressing mode represented
19845 // by AM is legal for this target, for a load/store of the specified type.
19846 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19847                                               const AddrMode &AM, Type *Ty,
19848                                               unsigned AS) const {
19849   // X86 supports extremely general addressing modes.
19850   CodeModel::Model M = getTargetMachine().getCodeModel();
19851   Reloc::Model R = getTargetMachine().getRelocationModel();
19852
19853   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19854   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19855     return false;
19856
19857   if (AM.BaseGV) {
19858     unsigned GVFlags =
19859       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19860
19861     // If a reference to this global requires an extra load, we can't fold it.
19862     if (isGlobalStubReference(GVFlags))
19863       return false;
19864
19865     // If BaseGV requires a register for the PIC base, we cannot also have a
19866     // BaseReg specified.
19867     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19868       return false;
19869
19870     // If lower 4G is not available, then we must use rip-relative addressing.
19871     if ((M != CodeModel::Small || R != Reloc::Static) &&
19872         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19873       return false;
19874   }
19875
19876   switch (AM.Scale) {
19877   case 0:
19878   case 1:
19879   case 2:
19880   case 4:
19881   case 8:
19882     // These scales always work.
19883     break;
19884   case 3:
19885   case 5:
19886   case 9:
19887     // These scales are formed with basereg+scalereg.  Only accept if there is
19888     // no basereg yet.
19889     if (AM.HasBaseReg)
19890       return false;
19891     break;
19892   default:  // Other stuff never works.
19893     return false;
19894   }
19895
19896   return true;
19897 }
19898
19899 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19900   unsigned Bits = Ty->getScalarSizeInBits();
19901
19902   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19903   // particularly cheaper than those without.
19904   if (Bits == 8)
19905     return false;
19906
19907   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19908   // variable shifts just as cheap as scalar ones.
19909   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19910     return false;
19911
19912   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19913   // fully general vector.
19914   return true;
19915 }
19916
19917 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19918   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19919     return false;
19920   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19921   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19922   return NumBits1 > NumBits2;
19923 }
19924
19925 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19926   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19927     return false;
19928
19929   if (!isTypeLegal(EVT::getEVT(Ty1)))
19930     return false;
19931
19932   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19933
19934   // Assuming the caller doesn't have a zeroext or signext return parameter,
19935   // truncation all the way down to i1 is valid.
19936   return true;
19937 }
19938
19939 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19940   return isInt<32>(Imm);
19941 }
19942
19943 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19944   // Can also use sub to handle negated immediates.
19945   return isInt<32>(Imm);
19946 }
19947
19948 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19949   if (!VT1.isInteger() || !VT2.isInteger())
19950     return false;
19951   unsigned NumBits1 = VT1.getSizeInBits();
19952   unsigned NumBits2 = VT2.getSizeInBits();
19953   return NumBits1 > NumBits2;
19954 }
19955
19956 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19957   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19958   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19959 }
19960
19961 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19962   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19963   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19964 }
19965
19966 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19967   EVT VT1 = Val.getValueType();
19968   if (isZExtFree(VT1, VT2))
19969     return true;
19970
19971   if (Val.getOpcode() != ISD::LOAD)
19972     return false;
19973
19974   if (!VT1.isSimple() || !VT1.isInteger() ||
19975       !VT2.isSimple() || !VT2.isInteger())
19976     return false;
19977
19978   switch (VT1.getSimpleVT().SimpleTy) {
19979   default: break;
19980   case MVT::i8:
19981   case MVT::i16:
19982   case MVT::i32:
19983     // X86 has 8, 16, and 32-bit zero-extending loads.
19984     return true;
19985   }
19986
19987   return false;
19988 }
19989
19990 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19991
19992 bool
19993 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19994   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19995     return false;
19996
19997   VT = VT.getScalarType();
19998
19999   if (!VT.isSimple())
20000     return false;
20001
20002   switch (VT.getSimpleVT().SimpleTy) {
20003   case MVT::f32:
20004   case MVT::f64:
20005     return true;
20006   default:
20007     break;
20008   }
20009
20010   return false;
20011 }
20012
20013 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20014   // i16 instructions are longer (0x66 prefix) and potentially slower.
20015   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20016 }
20017
20018 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20019 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20020 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20021 /// are assumed to be legal.
20022 bool
20023 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20024                                       EVT VT) const {
20025   if (!VT.isSimple())
20026     return false;
20027
20028   // Not for i1 vectors
20029   if (VT.getScalarType() == MVT::i1)
20030     return false;
20031
20032   // Very little shuffling can be done for 64-bit vectors right now.
20033   if (VT.getSizeInBits() == 64)
20034     return false;
20035
20036   // We only care that the types being shuffled are legal. The lowering can
20037   // handle any possible shuffle mask that results.
20038   return isTypeLegal(VT.getSimpleVT());
20039 }
20040
20041 bool
20042 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20043                                           EVT VT) const {
20044   // Just delegate to the generic legality, clear masks aren't special.
20045   return isShuffleMaskLegal(Mask, VT);
20046 }
20047
20048 //===----------------------------------------------------------------------===//
20049 //                           X86 Scheduler Hooks
20050 //===----------------------------------------------------------------------===//
20051
20052 /// Utility function to emit xbegin specifying the start of an RTM region.
20053 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20054                                      const TargetInstrInfo *TII) {
20055   DebugLoc DL = MI->getDebugLoc();
20056
20057   const BasicBlock *BB = MBB->getBasicBlock();
20058   MachineFunction::iterator I = MBB;
20059   ++I;
20060
20061   // For the v = xbegin(), we generate
20062   //
20063   // thisMBB:
20064   //  xbegin sinkMBB
20065   //
20066   // mainMBB:
20067   //  eax = -1
20068   //
20069   // sinkMBB:
20070   //  v = eax
20071
20072   MachineBasicBlock *thisMBB = MBB;
20073   MachineFunction *MF = MBB->getParent();
20074   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20075   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20076   MF->insert(I, mainMBB);
20077   MF->insert(I, sinkMBB);
20078
20079   // Transfer the remainder of BB and its successor edges to sinkMBB.
20080   sinkMBB->splice(sinkMBB->begin(), MBB,
20081                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20082   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20083
20084   // thisMBB:
20085   //  xbegin sinkMBB
20086   //  # fallthrough to mainMBB
20087   //  # abortion to sinkMBB
20088   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20089   thisMBB->addSuccessor(mainMBB);
20090   thisMBB->addSuccessor(sinkMBB);
20091
20092   // mainMBB:
20093   //  EAX = -1
20094   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20095   mainMBB->addSuccessor(sinkMBB);
20096
20097   // sinkMBB:
20098   // EAX is live into the sinkMBB
20099   sinkMBB->addLiveIn(X86::EAX);
20100   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20101           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20102     .addReg(X86::EAX);
20103
20104   MI->eraseFromParent();
20105   return sinkMBB;
20106 }
20107
20108 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20109 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20110 // in the .td file.
20111 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20112                                        const TargetInstrInfo *TII) {
20113   unsigned Opc;
20114   switch (MI->getOpcode()) {
20115   default: llvm_unreachable("illegal opcode!");
20116   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20117   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20118   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20119   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20120   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20121   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20122   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20123   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20124   }
20125
20126   DebugLoc dl = MI->getDebugLoc();
20127   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20128
20129   unsigned NumArgs = MI->getNumOperands();
20130   for (unsigned i = 1; i < NumArgs; ++i) {
20131     MachineOperand &Op = MI->getOperand(i);
20132     if (!(Op.isReg() && Op.isImplicit()))
20133       MIB.addOperand(Op);
20134   }
20135   if (MI->hasOneMemOperand())
20136     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20137
20138   BuildMI(*BB, MI, dl,
20139     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20140     .addReg(X86::XMM0);
20141
20142   MI->eraseFromParent();
20143   return BB;
20144 }
20145
20146 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20147 // defs in an instruction pattern
20148 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20149                                        const TargetInstrInfo *TII) {
20150   unsigned Opc;
20151   switch (MI->getOpcode()) {
20152   default: llvm_unreachable("illegal opcode!");
20153   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20154   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20155   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20156   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20157   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20158   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20159   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20160   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20161   }
20162
20163   DebugLoc dl = MI->getDebugLoc();
20164   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20165
20166   unsigned NumArgs = MI->getNumOperands(); // remove the results
20167   for (unsigned i = 1; i < NumArgs; ++i) {
20168     MachineOperand &Op = MI->getOperand(i);
20169     if (!(Op.isReg() && Op.isImplicit()))
20170       MIB.addOperand(Op);
20171   }
20172   if (MI->hasOneMemOperand())
20173     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20174
20175   BuildMI(*BB, MI, dl,
20176     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20177     .addReg(X86::ECX);
20178
20179   MI->eraseFromParent();
20180   return BB;
20181 }
20182
20183 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20184                                       const X86Subtarget *Subtarget) {
20185   DebugLoc dl = MI->getDebugLoc();
20186   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20187   // Address into RAX/EAX, other two args into ECX, EDX.
20188   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20189   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20190   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20191   for (int i = 0; i < X86::AddrNumOperands; ++i)
20192     MIB.addOperand(MI->getOperand(i));
20193
20194   unsigned ValOps = X86::AddrNumOperands;
20195   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20196     .addReg(MI->getOperand(ValOps).getReg());
20197   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20198     .addReg(MI->getOperand(ValOps+1).getReg());
20199
20200   // The instruction doesn't actually take any operands though.
20201   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20202
20203   MI->eraseFromParent(); // The pseudo is gone now.
20204   return BB;
20205 }
20206
20207 MachineBasicBlock *
20208 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20209                                                  MachineBasicBlock *MBB) const {
20210   // Emit va_arg instruction on X86-64.
20211
20212   // Operands to this pseudo-instruction:
20213   // 0  ) Output        : destination address (reg)
20214   // 1-5) Input         : va_list address (addr, i64mem)
20215   // 6  ) ArgSize       : Size (in bytes) of vararg type
20216   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20217   // 8  ) Align         : Alignment of type
20218   // 9  ) EFLAGS (implicit-def)
20219
20220   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20221   static_assert(X86::AddrNumOperands == 5,
20222                 "VAARG_64 assumes 5 address operands");
20223
20224   unsigned DestReg = MI->getOperand(0).getReg();
20225   MachineOperand &Base = MI->getOperand(1);
20226   MachineOperand &Scale = MI->getOperand(2);
20227   MachineOperand &Index = MI->getOperand(3);
20228   MachineOperand &Disp = MI->getOperand(4);
20229   MachineOperand &Segment = MI->getOperand(5);
20230   unsigned ArgSize = MI->getOperand(6).getImm();
20231   unsigned ArgMode = MI->getOperand(7).getImm();
20232   unsigned Align = MI->getOperand(8).getImm();
20233
20234   // Memory Reference
20235   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20236   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20237   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20238
20239   // Machine Information
20240   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20241   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20242   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20243   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20244   DebugLoc DL = MI->getDebugLoc();
20245
20246   // struct va_list {
20247   //   i32   gp_offset
20248   //   i32   fp_offset
20249   //   i64   overflow_area (address)
20250   //   i64   reg_save_area (address)
20251   // }
20252   // sizeof(va_list) = 24
20253   // alignment(va_list) = 8
20254
20255   unsigned TotalNumIntRegs = 6;
20256   unsigned TotalNumXMMRegs = 8;
20257   bool UseGPOffset = (ArgMode == 1);
20258   bool UseFPOffset = (ArgMode == 2);
20259   unsigned MaxOffset = TotalNumIntRegs * 8 +
20260                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20261
20262   /* Align ArgSize to a multiple of 8 */
20263   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20264   bool NeedsAlign = (Align > 8);
20265
20266   MachineBasicBlock *thisMBB = MBB;
20267   MachineBasicBlock *overflowMBB;
20268   MachineBasicBlock *offsetMBB;
20269   MachineBasicBlock *endMBB;
20270
20271   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20272   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20273   unsigned OffsetReg = 0;
20274
20275   if (!UseGPOffset && !UseFPOffset) {
20276     // If we only pull from the overflow region, we don't create a branch.
20277     // We don't need to alter control flow.
20278     OffsetDestReg = 0; // unused
20279     OverflowDestReg = DestReg;
20280
20281     offsetMBB = nullptr;
20282     overflowMBB = thisMBB;
20283     endMBB = thisMBB;
20284   } else {
20285     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20286     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20287     // If not, pull from overflow_area. (branch to overflowMBB)
20288     //
20289     //       thisMBB
20290     //         |     .
20291     //         |        .
20292     //     offsetMBB   overflowMBB
20293     //         |        .
20294     //         |     .
20295     //        endMBB
20296
20297     // Registers for the PHI in endMBB
20298     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20299     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20300
20301     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20302     MachineFunction *MF = MBB->getParent();
20303     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20304     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20305     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20306
20307     MachineFunction::iterator MBBIter = MBB;
20308     ++MBBIter;
20309
20310     // Insert the new basic blocks
20311     MF->insert(MBBIter, offsetMBB);
20312     MF->insert(MBBIter, overflowMBB);
20313     MF->insert(MBBIter, endMBB);
20314
20315     // Transfer the remainder of MBB and its successor edges to endMBB.
20316     endMBB->splice(endMBB->begin(), thisMBB,
20317                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20318     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20319
20320     // Make offsetMBB and overflowMBB successors of thisMBB
20321     thisMBB->addSuccessor(offsetMBB);
20322     thisMBB->addSuccessor(overflowMBB);
20323
20324     // endMBB is a successor of both offsetMBB and overflowMBB
20325     offsetMBB->addSuccessor(endMBB);
20326     overflowMBB->addSuccessor(endMBB);
20327
20328     // Load the offset value into a register
20329     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20330     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20331       .addOperand(Base)
20332       .addOperand(Scale)
20333       .addOperand(Index)
20334       .addDisp(Disp, UseFPOffset ? 4 : 0)
20335       .addOperand(Segment)
20336       .setMemRefs(MMOBegin, MMOEnd);
20337
20338     // Check if there is enough room left to pull this argument.
20339     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20340       .addReg(OffsetReg)
20341       .addImm(MaxOffset + 8 - ArgSizeA8);
20342
20343     // Branch to "overflowMBB" if offset >= max
20344     // Fall through to "offsetMBB" otherwise
20345     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20346       .addMBB(overflowMBB);
20347   }
20348
20349   // In offsetMBB, emit code to use the reg_save_area.
20350   if (offsetMBB) {
20351     assert(OffsetReg != 0);
20352
20353     // Read the reg_save_area address.
20354     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20355     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20356       .addOperand(Base)
20357       .addOperand(Scale)
20358       .addOperand(Index)
20359       .addDisp(Disp, 16)
20360       .addOperand(Segment)
20361       .setMemRefs(MMOBegin, MMOEnd);
20362
20363     // Zero-extend the offset
20364     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20365       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20366         .addImm(0)
20367         .addReg(OffsetReg)
20368         .addImm(X86::sub_32bit);
20369
20370     // Add the offset to the reg_save_area to get the final address.
20371     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20372       .addReg(OffsetReg64)
20373       .addReg(RegSaveReg);
20374
20375     // Compute the offset for the next argument
20376     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20377     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20378       .addReg(OffsetReg)
20379       .addImm(UseFPOffset ? 16 : 8);
20380
20381     // Store it back into the va_list.
20382     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20383       .addOperand(Base)
20384       .addOperand(Scale)
20385       .addOperand(Index)
20386       .addDisp(Disp, UseFPOffset ? 4 : 0)
20387       .addOperand(Segment)
20388       .addReg(NextOffsetReg)
20389       .setMemRefs(MMOBegin, MMOEnd);
20390
20391     // Jump to endMBB
20392     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20393       .addMBB(endMBB);
20394   }
20395
20396   //
20397   // Emit code to use overflow area
20398   //
20399
20400   // Load the overflow_area address into a register.
20401   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20402   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20403     .addOperand(Base)
20404     .addOperand(Scale)
20405     .addOperand(Index)
20406     .addDisp(Disp, 8)
20407     .addOperand(Segment)
20408     .setMemRefs(MMOBegin, MMOEnd);
20409
20410   // If we need to align it, do so. Otherwise, just copy the address
20411   // to OverflowDestReg.
20412   if (NeedsAlign) {
20413     // Align the overflow address
20414     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20415     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20416
20417     // aligned_addr = (addr + (align-1)) & ~(align-1)
20418     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20419       .addReg(OverflowAddrReg)
20420       .addImm(Align-1);
20421
20422     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20423       .addReg(TmpReg)
20424       .addImm(~(uint64_t)(Align-1));
20425   } else {
20426     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20427       .addReg(OverflowAddrReg);
20428   }
20429
20430   // Compute the next overflow address after this argument.
20431   // (the overflow address should be kept 8-byte aligned)
20432   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20433   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20434     .addReg(OverflowDestReg)
20435     .addImm(ArgSizeA8);
20436
20437   // Store the new overflow address.
20438   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20439     .addOperand(Base)
20440     .addOperand(Scale)
20441     .addOperand(Index)
20442     .addDisp(Disp, 8)
20443     .addOperand(Segment)
20444     .addReg(NextAddrReg)
20445     .setMemRefs(MMOBegin, MMOEnd);
20446
20447   // If we branched, emit the PHI to the front of endMBB.
20448   if (offsetMBB) {
20449     BuildMI(*endMBB, endMBB->begin(), DL,
20450             TII->get(X86::PHI), DestReg)
20451       .addReg(OffsetDestReg).addMBB(offsetMBB)
20452       .addReg(OverflowDestReg).addMBB(overflowMBB);
20453   }
20454
20455   // Erase the pseudo instruction
20456   MI->eraseFromParent();
20457
20458   return endMBB;
20459 }
20460
20461 MachineBasicBlock *
20462 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20463                                                  MachineInstr *MI,
20464                                                  MachineBasicBlock *MBB) const {
20465   // Emit code to save XMM registers to the stack. The ABI says that the
20466   // number of registers to save is given in %al, so it's theoretically
20467   // possible to do an indirect jump trick to avoid saving all of them,
20468   // however this code takes a simpler approach and just executes all
20469   // of the stores if %al is non-zero. It's less code, and it's probably
20470   // easier on the hardware branch predictor, and stores aren't all that
20471   // expensive anyway.
20472
20473   // Create the new basic blocks. One block contains all the XMM stores,
20474   // and one block is the final destination regardless of whether any
20475   // stores were performed.
20476   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20477   MachineFunction *F = MBB->getParent();
20478   MachineFunction::iterator MBBIter = MBB;
20479   ++MBBIter;
20480   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20481   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20482   F->insert(MBBIter, XMMSaveMBB);
20483   F->insert(MBBIter, EndMBB);
20484
20485   // Transfer the remainder of MBB and its successor edges to EndMBB.
20486   EndMBB->splice(EndMBB->begin(), MBB,
20487                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20488   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20489
20490   // The original block will now fall through to the XMM save block.
20491   MBB->addSuccessor(XMMSaveMBB);
20492   // The XMMSaveMBB will fall through to the end block.
20493   XMMSaveMBB->addSuccessor(EndMBB);
20494
20495   // Now add the instructions.
20496   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20497   DebugLoc DL = MI->getDebugLoc();
20498
20499   unsigned CountReg = MI->getOperand(0).getReg();
20500   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20501   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20502
20503   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20504     // If %al is 0, branch around the XMM save block.
20505     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20506     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20507     MBB->addSuccessor(EndMBB);
20508   }
20509
20510   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20511   // that was just emitted, but clearly shouldn't be "saved".
20512   assert((MI->getNumOperands() <= 3 ||
20513           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20514           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20515          && "Expected last argument to be EFLAGS");
20516   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20517   // In the XMM save block, save all the XMM argument registers.
20518   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20519     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20520     MachineMemOperand *MMO = F->getMachineMemOperand(
20521         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20522         MachineMemOperand::MOStore,
20523         /*Size=*/16, /*Align=*/16);
20524     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20525       .addFrameIndex(RegSaveFrameIndex)
20526       .addImm(/*Scale=*/1)
20527       .addReg(/*IndexReg=*/0)
20528       .addImm(/*Disp=*/Offset)
20529       .addReg(/*Segment=*/0)
20530       .addReg(MI->getOperand(i).getReg())
20531       .addMemOperand(MMO);
20532   }
20533
20534   MI->eraseFromParent();   // The pseudo instruction is gone now.
20535
20536   return EndMBB;
20537 }
20538
20539 // The EFLAGS operand of SelectItr might be missing a kill marker
20540 // because there were multiple uses of EFLAGS, and ISel didn't know
20541 // which to mark. Figure out whether SelectItr should have had a
20542 // kill marker, and set it if it should. Returns the correct kill
20543 // marker value.
20544 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20545                                      MachineBasicBlock* BB,
20546                                      const TargetRegisterInfo* TRI) {
20547   // Scan forward through BB for a use/def of EFLAGS.
20548   MachineBasicBlock::iterator miI(std::next(SelectItr));
20549   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20550     const MachineInstr& mi = *miI;
20551     if (mi.readsRegister(X86::EFLAGS))
20552       return false;
20553     if (mi.definesRegister(X86::EFLAGS))
20554       break; // Should have kill-flag - update below.
20555   }
20556
20557   // If we hit the end of the block, check whether EFLAGS is live into a
20558   // successor.
20559   if (miI == BB->end()) {
20560     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20561                                           sEnd = BB->succ_end();
20562          sItr != sEnd; ++sItr) {
20563       MachineBasicBlock* succ = *sItr;
20564       if (succ->isLiveIn(X86::EFLAGS))
20565         return false;
20566     }
20567   }
20568
20569   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20570   // out. SelectMI should have a kill flag on EFLAGS.
20571   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20572   return true;
20573 }
20574
20575 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20576 // together with other CMOV pseudo-opcodes into a single basic-block with
20577 // conditional jump around it.
20578 static bool isCMOVPseudo(MachineInstr *MI) {
20579   switch (MI->getOpcode()) {
20580   case X86::CMOV_FR32:
20581   case X86::CMOV_FR64:
20582   case X86::CMOV_GR8:
20583   case X86::CMOV_GR16:
20584   case X86::CMOV_GR32:
20585   case X86::CMOV_RFP32:
20586   case X86::CMOV_RFP64:
20587   case X86::CMOV_RFP80:
20588   case X86::CMOV_V2F64:
20589   case X86::CMOV_V2I64:
20590   case X86::CMOV_V4F32:
20591   case X86::CMOV_V4F64:
20592   case X86::CMOV_V4I64:
20593   case X86::CMOV_V16F32:
20594   case X86::CMOV_V8F32:
20595   case X86::CMOV_V8F64:
20596   case X86::CMOV_V8I64:
20597   case X86::CMOV_V8I1:
20598   case X86::CMOV_V16I1:
20599   case X86::CMOV_V32I1:
20600   case X86::CMOV_V64I1:
20601     return true;
20602
20603   default:
20604     return false;
20605   }
20606 }
20607
20608 MachineBasicBlock *
20609 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20610                                      MachineBasicBlock *BB) const {
20611   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20612   DebugLoc DL = MI->getDebugLoc();
20613
20614   // To "insert" a SELECT_CC instruction, we actually have to insert the
20615   // diamond control-flow pattern.  The incoming instruction knows the
20616   // destination vreg to set, the condition code register to branch on, the
20617   // true/false values to select between, and a branch opcode to use.
20618   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20619   MachineFunction::iterator It = BB;
20620   ++It;
20621
20622   //  thisMBB:
20623   //  ...
20624   //   TrueVal = ...
20625   //   cmpTY ccX, r1, r2
20626   //   bCC copy1MBB
20627   //   fallthrough --> copy0MBB
20628   MachineBasicBlock *thisMBB = BB;
20629   MachineFunction *F = BB->getParent();
20630
20631   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20632   // as described above, by inserting a BB, and then making a PHI at the join
20633   // point to select the true and false operands of the CMOV in the PHI.
20634   //
20635   // The code also handles two different cases of multiple CMOV opcodes
20636   // in a row.
20637   //
20638   // Case 1:
20639   // In this case, there are multiple CMOVs in a row, all which are based on
20640   // the same condition setting (or the exact opposite condition setting).
20641   // In this case we can lower all the CMOVs using a single inserted BB, and
20642   // then make a number of PHIs at the join point to model the CMOVs. The only
20643   // trickiness here, is that in a case like:
20644   //
20645   // t2 = CMOV cond1 t1, f1
20646   // t3 = CMOV cond1 t2, f2
20647   //
20648   // when rewriting this into PHIs, we have to perform some renaming on the
20649   // temps since you cannot have a PHI operand refer to a PHI result earlier
20650   // in the same block.  The "simple" but wrong lowering would be:
20651   //
20652   // t2 = PHI t1(BB1), f1(BB2)
20653   // t3 = PHI t2(BB1), f2(BB2)
20654   //
20655   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20656   // renaming is to note that on the path through BB1, t2 is really just a
20657   // copy of t1, and do that renaming, properly generating:
20658   //
20659   // t2 = PHI t1(BB1), f1(BB2)
20660   // t3 = PHI t1(BB1), f2(BB2)
20661   //
20662   // Case 2, we lower cascaded CMOVs such as
20663   //
20664   //   (CMOV (CMOV F, T, cc1), T, cc2)
20665   //
20666   // to two successives branches.  For that, we look for another CMOV as the
20667   // following instruction.
20668   //
20669   // Without this, we would add a PHI between the two jumps, which ends up
20670   // creating a few copies all around. For instance, for
20671   //
20672   //    (sitofp (zext (fcmp une)))
20673   //
20674   // we would generate:
20675   //
20676   //         ucomiss %xmm1, %xmm0
20677   //         movss  <1.0f>, %xmm0
20678   //         movaps  %xmm0, %xmm1
20679   //         jne     .LBB5_2
20680   //         xorps   %xmm1, %xmm1
20681   // .LBB5_2:
20682   //         jp      .LBB5_4
20683   //         movaps  %xmm1, %xmm0
20684   // .LBB5_4:
20685   //         retq
20686   //
20687   // because this custom-inserter would have generated:
20688   //
20689   //   A
20690   //   | \
20691   //   |  B
20692   //   | /
20693   //   C
20694   //   | \
20695   //   |  D
20696   //   | /
20697   //   E
20698   //
20699   // A: X = ...; Y = ...
20700   // B: empty
20701   // C: Z = PHI [X, A], [Y, B]
20702   // D: empty
20703   // E: PHI [X, C], [Z, D]
20704   //
20705   // If we lower both CMOVs in a single step, we can instead generate:
20706   //
20707   //   A
20708   //   | \
20709   //   |  C
20710   //   | /|
20711   //   |/ |
20712   //   |  |
20713   //   |  D
20714   //   | /
20715   //   E
20716   //
20717   // A: X = ...; Y = ...
20718   // D: empty
20719   // E: PHI [X, A], [X, C], [Y, D]
20720   //
20721   // Which, in our sitofp/fcmp example, gives us something like:
20722   //
20723   //         ucomiss %xmm1, %xmm0
20724   //         movss  <1.0f>, %xmm0
20725   //         jne     .LBB5_4
20726   //         jp      .LBB5_4
20727   //         xorps   %xmm0, %xmm0
20728   // .LBB5_4:
20729   //         retq
20730   //
20731   MachineInstr *CascadedCMOV = nullptr;
20732   MachineInstr *LastCMOV = MI;
20733   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20734   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20735   MachineBasicBlock::iterator NextMIIt =
20736       std::next(MachineBasicBlock::iterator(MI));
20737
20738   // Check for case 1, where there are multiple CMOVs with the same condition
20739   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20740   // number of jumps the most.
20741
20742   if (isCMOVPseudo(MI)) {
20743     // See if we have a string of CMOVS with the same condition.
20744     while (NextMIIt != BB->end() &&
20745            isCMOVPseudo(NextMIIt) &&
20746            (NextMIIt->getOperand(3).getImm() == CC ||
20747             NextMIIt->getOperand(3).getImm() == OppCC)) {
20748       LastCMOV = &*NextMIIt;
20749       ++NextMIIt;
20750     }
20751   }
20752
20753   // This checks for case 2, but only do this if we didn't already find
20754   // case 1, as indicated by LastCMOV == MI.
20755   if (LastCMOV == MI &&
20756       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20757       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20758       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20759     CascadedCMOV = &*NextMIIt;
20760   }
20761
20762   MachineBasicBlock *jcc1MBB = nullptr;
20763
20764   // If we have a cascaded CMOV, we lower it to two successive branches to
20765   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20766   if (CascadedCMOV) {
20767     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20768     F->insert(It, jcc1MBB);
20769     jcc1MBB->addLiveIn(X86::EFLAGS);
20770   }
20771
20772   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20773   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20774   F->insert(It, copy0MBB);
20775   F->insert(It, sinkMBB);
20776
20777   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20778   // live into the sink and copy blocks.
20779   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20780
20781   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20782   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20783       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20784     copy0MBB->addLiveIn(X86::EFLAGS);
20785     sinkMBB->addLiveIn(X86::EFLAGS);
20786   }
20787
20788   // Transfer the remainder of BB and its successor edges to sinkMBB.
20789   sinkMBB->splice(sinkMBB->begin(), BB,
20790                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20791   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20792
20793   // Add the true and fallthrough blocks as its successors.
20794   if (CascadedCMOV) {
20795     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20796     BB->addSuccessor(jcc1MBB);
20797
20798     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20799     // jump to the sinkMBB.
20800     jcc1MBB->addSuccessor(copy0MBB);
20801     jcc1MBB->addSuccessor(sinkMBB);
20802   } else {
20803     BB->addSuccessor(copy0MBB);
20804   }
20805
20806   // The true block target of the first (or only) branch is always sinkMBB.
20807   BB->addSuccessor(sinkMBB);
20808
20809   // Create the conditional branch instruction.
20810   unsigned Opc = X86::GetCondBranchFromCond(CC);
20811   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20812
20813   if (CascadedCMOV) {
20814     unsigned Opc2 = X86::GetCondBranchFromCond(
20815         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20816     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20817   }
20818
20819   //  copy0MBB:
20820   //   %FalseValue = ...
20821   //   # fallthrough to sinkMBB
20822   copy0MBB->addSuccessor(sinkMBB);
20823
20824   //  sinkMBB:
20825   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20826   //  ...
20827   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20828   MachineBasicBlock::iterator MIItEnd =
20829     std::next(MachineBasicBlock::iterator(LastCMOV));
20830   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20831   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20832   MachineInstrBuilder MIB;
20833
20834   // As we are creating the PHIs, we have to be careful if there is more than
20835   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20836   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20837   // That also means that PHI construction must work forward from earlier to
20838   // later, and that the code must maintain a mapping from earlier PHI's
20839   // destination registers, and the registers that went into the PHI.
20840
20841   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20842     unsigned DestReg = MIIt->getOperand(0).getReg();
20843     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20844     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20845
20846     // If this CMOV we are generating is the opposite condition from
20847     // the jump we generated, then we have to swap the operands for the
20848     // PHI that is going to be generated.
20849     if (MIIt->getOperand(3).getImm() == OppCC)
20850         std::swap(Op1Reg, Op2Reg);
20851
20852     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20853       Op1Reg = RegRewriteTable[Op1Reg].first;
20854
20855     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20856       Op2Reg = RegRewriteTable[Op2Reg].second;
20857
20858     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20859                   TII->get(X86::PHI), DestReg)
20860           .addReg(Op1Reg).addMBB(copy0MBB)
20861           .addReg(Op2Reg).addMBB(thisMBB);
20862
20863     // Add this PHI to the rewrite table.
20864     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20865   }
20866
20867   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20868   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20869   if (CascadedCMOV) {
20870     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20871     // Copy the PHI result to the register defined by the second CMOV.
20872     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20873             DL, TII->get(TargetOpcode::COPY),
20874             CascadedCMOV->getOperand(0).getReg())
20875         .addReg(MI->getOperand(0).getReg());
20876     CascadedCMOV->eraseFromParent();
20877   }
20878
20879   // Now remove the CMOV(s).
20880   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20881     (MIIt++)->eraseFromParent();
20882
20883   return sinkMBB;
20884 }
20885
20886 MachineBasicBlock *
20887 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20888                                        MachineBasicBlock *BB) const {
20889   // Combine the following atomic floating-point modification pattern:
20890   //   a.store(reg OP a.load(acquire), release)
20891   // Transform them into:
20892   //   OPss (%gpr), %xmm
20893   //   movss %xmm, (%gpr)
20894   // Or sd equivalent for 64-bit operations.
20895   unsigned MOp, FOp;
20896   switch (MI->getOpcode()) {
20897   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20898   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20899   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20900   }
20901   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20902   DebugLoc DL = MI->getDebugLoc();
20903   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20904   unsigned MSrc = MI->getOperand(0).getReg();
20905   unsigned VSrc = MI->getOperand(5).getReg();
20906   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20907                                 .addReg(/*Base=*/MSrc)
20908                                 .addImm(/*Scale=*/1)
20909                                 .addReg(/*Index=*/0)
20910                                 .addImm(0)
20911                                 .addReg(0);
20912   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20913                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20914                           .addReg(VSrc)
20915                           .addReg(/*Base=*/MSrc)
20916                           .addImm(/*Scale=*/1)
20917                           .addReg(/*Index=*/0)
20918                           .addImm(/*Disp=*/0)
20919                           .addReg(/*Segment=*/0);
20920   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20921   MI->eraseFromParent(); // The pseudo instruction is gone now.
20922   return BB;
20923 }
20924
20925 MachineBasicBlock *
20926 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20927                                         MachineBasicBlock *BB) const {
20928   MachineFunction *MF = BB->getParent();
20929   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20930   DebugLoc DL = MI->getDebugLoc();
20931   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20932
20933   assert(MF->shouldSplitStack());
20934
20935   const bool Is64Bit = Subtarget->is64Bit();
20936   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20937
20938   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20939   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20940
20941   // BB:
20942   //  ... [Till the alloca]
20943   // If stacklet is not large enough, jump to mallocMBB
20944   //
20945   // bumpMBB:
20946   //  Allocate by subtracting from RSP
20947   //  Jump to continueMBB
20948   //
20949   // mallocMBB:
20950   //  Allocate by call to runtime
20951   //
20952   // continueMBB:
20953   //  ...
20954   //  [rest of original BB]
20955   //
20956
20957   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20958   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20959   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20960
20961   MachineRegisterInfo &MRI = MF->getRegInfo();
20962   const TargetRegisterClass *AddrRegClass =
20963       getRegClassFor(getPointerTy(MF->getDataLayout()));
20964
20965   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20966     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20967     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20968     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20969     sizeVReg = MI->getOperand(1).getReg(),
20970     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20971
20972   MachineFunction::iterator MBBIter = BB;
20973   ++MBBIter;
20974
20975   MF->insert(MBBIter, bumpMBB);
20976   MF->insert(MBBIter, mallocMBB);
20977   MF->insert(MBBIter, continueMBB);
20978
20979   continueMBB->splice(continueMBB->begin(), BB,
20980                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20981   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20982
20983   // Add code to the main basic block to check if the stack limit has been hit,
20984   // and if so, jump to mallocMBB otherwise to bumpMBB.
20985   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20986   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20987     .addReg(tmpSPVReg).addReg(sizeVReg);
20988   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20989     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20990     .addReg(SPLimitVReg);
20991   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20992
20993   // bumpMBB simply decreases the stack pointer, since we know the current
20994   // stacklet has enough space.
20995   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20996     .addReg(SPLimitVReg);
20997   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20998     .addReg(SPLimitVReg);
20999   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21000
21001   // Calls into a routine in libgcc to allocate more space from the heap.
21002   const uint32_t *RegMask =
21003       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21004   if (IsLP64) {
21005     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21006       .addReg(sizeVReg);
21007     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21008       .addExternalSymbol("__morestack_allocate_stack_space")
21009       .addRegMask(RegMask)
21010       .addReg(X86::RDI, RegState::Implicit)
21011       .addReg(X86::RAX, RegState::ImplicitDefine);
21012   } else if (Is64Bit) {
21013     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21014       .addReg(sizeVReg);
21015     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21016       .addExternalSymbol("__morestack_allocate_stack_space")
21017       .addRegMask(RegMask)
21018       .addReg(X86::EDI, RegState::Implicit)
21019       .addReg(X86::EAX, RegState::ImplicitDefine);
21020   } else {
21021     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21022       .addImm(12);
21023     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21024     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21025       .addExternalSymbol("__morestack_allocate_stack_space")
21026       .addRegMask(RegMask)
21027       .addReg(X86::EAX, RegState::ImplicitDefine);
21028   }
21029
21030   if (!Is64Bit)
21031     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21032       .addImm(16);
21033
21034   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21035     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21036   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21037
21038   // Set up the CFG correctly.
21039   BB->addSuccessor(bumpMBB);
21040   BB->addSuccessor(mallocMBB);
21041   mallocMBB->addSuccessor(continueMBB);
21042   bumpMBB->addSuccessor(continueMBB);
21043
21044   // Take care of the PHI nodes.
21045   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21046           MI->getOperand(0).getReg())
21047     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21048     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21049
21050   // Delete the original pseudo instruction.
21051   MI->eraseFromParent();
21052
21053   // And we're done.
21054   return continueMBB;
21055 }
21056
21057 MachineBasicBlock *
21058 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21059                                         MachineBasicBlock *BB) const {
21060   DebugLoc DL = MI->getDebugLoc();
21061
21062   assert(!Subtarget->isTargetMachO());
21063
21064   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21065                                                     DL);
21066
21067   MI->eraseFromParent();   // The pseudo instruction is gone now.
21068   return BB;
21069 }
21070
21071 MachineBasicBlock *
21072 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21073                                       MachineBasicBlock *BB) const {
21074   // This is pretty easy.  We're taking the value that we received from
21075   // our load from the relocation, sticking it in either RDI (x86-64)
21076   // or EAX and doing an indirect call.  The return value will then
21077   // be in the normal return register.
21078   MachineFunction *F = BB->getParent();
21079   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21080   DebugLoc DL = MI->getDebugLoc();
21081
21082   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21083   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21084
21085   // Get a register mask for the lowered call.
21086   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21087   // proper register mask.
21088   const uint32_t *RegMask =
21089       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21090   if (Subtarget->is64Bit()) {
21091     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21092                                       TII->get(X86::MOV64rm), X86::RDI)
21093     .addReg(X86::RIP)
21094     .addImm(0).addReg(0)
21095     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21096                       MI->getOperand(3).getTargetFlags())
21097     .addReg(0);
21098     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21099     addDirectMem(MIB, X86::RDI);
21100     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21101   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21102     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21103                                       TII->get(X86::MOV32rm), X86::EAX)
21104     .addReg(0)
21105     .addImm(0).addReg(0)
21106     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21107                       MI->getOperand(3).getTargetFlags())
21108     .addReg(0);
21109     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21110     addDirectMem(MIB, X86::EAX);
21111     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21112   } else {
21113     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21114                                       TII->get(X86::MOV32rm), X86::EAX)
21115     .addReg(TII->getGlobalBaseReg(F))
21116     .addImm(0).addReg(0)
21117     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21118                       MI->getOperand(3).getTargetFlags())
21119     .addReg(0);
21120     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21121     addDirectMem(MIB, X86::EAX);
21122     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21123   }
21124
21125   MI->eraseFromParent(); // The pseudo instruction is gone now.
21126   return BB;
21127 }
21128
21129 MachineBasicBlock *
21130 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21131                                     MachineBasicBlock *MBB) const {
21132   DebugLoc DL = MI->getDebugLoc();
21133   MachineFunction *MF = MBB->getParent();
21134   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21135   MachineRegisterInfo &MRI = MF->getRegInfo();
21136
21137   const BasicBlock *BB = MBB->getBasicBlock();
21138   MachineFunction::iterator I = MBB;
21139   ++I;
21140
21141   // Memory Reference
21142   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21143   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21144
21145   unsigned DstReg;
21146   unsigned MemOpndSlot = 0;
21147
21148   unsigned CurOp = 0;
21149
21150   DstReg = MI->getOperand(CurOp++).getReg();
21151   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21152   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21153   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21154   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21155
21156   MemOpndSlot = CurOp;
21157
21158   MVT PVT = getPointerTy(MF->getDataLayout());
21159   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21160          "Invalid Pointer Size!");
21161
21162   // For v = setjmp(buf), we generate
21163   //
21164   // thisMBB:
21165   //  buf[LabelOffset] = restoreMBB
21166   //  SjLjSetup restoreMBB
21167   //
21168   // mainMBB:
21169   //  v_main = 0
21170   //
21171   // sinkMBB:
21172   //  v = phi(main, restore)
21173   //
21174   // restoreMBB:
21175   //  if base pointer being used, load it from frame
21176   //  v_restore = 1
21177
21178   MachineBasicBlock *thisMBB = MBB;
21179   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21180   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21181   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21182   MF->insert(I, mainMBB);
21183   MF->insert(I, sinkMBB);
21184   MF->push_back(restoreMBB);
21185
21186   MachineInstrBuilder MIB;
21187
21188   // Transfer the remainder of BB and its successor edges to sinkMBB.
21189   sinkMBB->splice(sinkMBB->begin(), MBB,
21190                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21191   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21192
21193   // thisMBB:
21194   unsigned PtrStoreOpc = 0;
21195   unsigned LabelReg = 0;
21196   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21197   Reloc::Model RM = MF->getTarget().getRelocationModel();
21198   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21199                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21200
21201   // Prepare IP either in reg or imm.
21202   if (!UseImmLabel) {
21203     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21204     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21205     LabelReg = MRI.createVirtualRegister(PtrRC);
21206     if (Subtarget->is64Bit()) {
21207       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21208               .addReg(X86::RIP)
21209               .addImm(0)
21210               .addReg(0)
21211               .addMBB(restoreMBB)
21212               .addReg(0);
21213     } else {
21214       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21215       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21216               .addReg(XII->getGlobalBaseReg(MF))
21217               .addImm(0)
21218               .addReg(0)
21219               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21220               .addReg(0);
21221     }
21222   } else
21223     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21224   // Store IP
21225   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21226   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21227     if (i == X86::AddrDisp)
21228       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21229     else
21230       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21231   }
21232   if (!UseImmLabel)
21233     MIB.addReg(LabelReg);
21234   else
21235     MIB.addMBB(restoreMBB);
21236   MIB.setMemRefs(MMOBegin, MMOEnd);
21237   // Setup
21238   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21239           .addMBB(restoreMBB);
21240
21241   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21242   MIB.addRegMask(RegInfo->getNoPreservedMask());
21243   thisMBB->addSuccessor(mainMBB);
21244   thisMBB->addSuccessor(restoreMBB);
21245
21246   // mainMBB:
21247   //  EAX = 0
21248   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21249   mainMBB->addSuccessor(sinkMBB);
21250
21251   // sinkMBB:
21252   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21253           TII->get(X86::PHI), DstReg)
21254     .addReg(mainDstReg).addMBB(mainMBB)
21255     .addReg(restoreDstReg).addMBB(restoreMBB);
21256
21257   // restoreMBB:
21258   if (RegInfo->hasBasePointer(*MF)) {
21259     const bool Uses64BitFramePtr =
21260         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21261     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21262     X86FI->setRestoreBasePointer(MF);
21263     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21264     unsigned BasePtr = RegInfo->getBaseRegister();
21265     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21266     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21267                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21268       .setMIFlag(MachineInstr::FrameSetup);
21269   }
21270   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21271   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21272   restoreMBB->addSuccessor(sinkMBB);
21273
21274   MI->eraseFromParent();
21275   return sinkMBB;
21276 }
21277
21278 MachineBasicBlock *
21279 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21280                                      MachineBasicBlock *MBB) const {
21281   DebugLoc DL = MI->getDebugLoc();
21282   MachineFunction *MF = MBB->getParent();
21283   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21284   MachineRegisterInfo &MRI = MF->getRegInfo();
21285
21286   // Memory Reference
21287   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21288   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21289
21290   MVT PVT = getPointerTy(MF->getDataLayout());
21291   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21292          "Invalid Pointer Size!");
21293
21294   const TargetRegisterClass *RC =
21295     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21296   unsigned Tmp = MRI.createVirtualRegister(RC);
21297   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21298   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21299   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21300   unsigned SP = RegInfo->getStackRegister();
21301
21302   MachineInstrBuilder MIB;
21303
21304   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21305   const int64_t SPOffset = 2 * PVT.getStoreSize();
21306
21307   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21308   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21309
21310   // Reload FP
21311   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21312   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21313     MIB.addOperand(MI->getOperand(i));
21314   MIB.setMemRefs(MMOBegin, MMOEnd);
21315   // Reload IP
21316   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21317   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21318     if (i == X86::AddrDisp)
21319       MIB.addDisp(MI->getOperand(i), LabelOffset);
21320     else
21321       MIB.addOperand(MI->getOperand(i));
21322   }
21323   MIB.setMemRefs(MMOBegin, MMOEnd);
21324   // Reload SP
21325   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21326   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21327     if (i == X86::AddrDisp)
21328       MIB.addDisp(MI->getOperand(i), SPOffset);
21329     else
21330       MIB.addOperand(MI->getOperand(i));
21331   }
21332   MIB.setMemRefs(MMOBegin, MMOEnd);
21333   // Jump
21334   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21335
21336   MI->eraseFromParent();
21337   return MBB;
21338 }
21339
21340 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21341 // accumulator loops. Writing back to the accumulator allows the coalescer
21342 // to remove extra copies in the loop.
21343 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21344 MachineBasicBlock *
21345 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21346                                  MachineBasicBlock *MBB) const {
21347   MachineOperand &AddendOp = MI->getOperand(3);
21348
21349   // Bail out early if the addend isn't a register - we can't switch these.
21350   if (!AddendOp.isReg())
21351     return MBB;
21352
21353   MachineFunction &MF = *MBB->getParent();
21354   MachineRegisterInfo &MRI = MF.getRegInfo();
21355
21356   // Check whether the addend is defined by a PHI:
21357   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21358   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21359   if (!AddendDef.isPHI())
21360     return MBB;
21361
21362   // Look for the following pattern:
21363   // loop:
21364   //   %addend = phi [%entry, 0], [%loop, %result]
21365   //   ...
21366   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21367
21368   // Replace with:
21369   //   loop:
21370   //   %addend = phi [%entry, 0], [%loop, %result]
21371   //   ...
21372   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21373
21374   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21375     assert(AddendDef.getOperand(i).isReg());
21376     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21377     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21378     if (&PHISrcInst == MI) {
21379       // Found a matching instruction.
21380       unsigned NewFMAOpc = 0;
21381       switch (MI->getOpcode()) {
21382         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21383         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21384         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21385         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21386         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21387         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21388         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21389         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21390         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21391         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21392         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21393         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21394         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21395         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21396         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21397         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21398         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21399         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21400         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21401         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21402
21403         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21404         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21405         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21406         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21407         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21408         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21409         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21410         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21411         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21412         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21413         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21414         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21415         default: llvm_unreachable("Unrecognized FMA variant.");
21416       }
21417
21418       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21419       MachineInstrBuilder MIB =
21420         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21421         .addOperand(MI->getOperand(0))
21422         .addOperand(MI->getOperand(3))
21423         .addOperand(MI->getOperand(2))
21424         .addOperand(MI->getOperand(1));
21425       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21426       MI->eraseFromParent();
21427     }
21428   }
21429
21430   return MBB;
21431 }
21432
21433 MachineBasicBlock *
21434 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21435                                                MachineBasicBlock *BB) const {
21436   switch (MI->getOpcode()) {
21437   default: llvm_unreachable("Unexpected instr type to insert");
21438   case X86::TAILJMPd64:
21439   case X86::TAILJMPr64:
21440   case X86::TAILJMPm64:
21441   case X86::TAILJMPd64_REX:
21442   case X86::TAILJMPr64_REX:
21443   case X86::TAILJMPm64_REX:
21444     llvm_unreachable("TAILJMP64 would not be touched here.");
21445   case X86::TCRETURNdi64:
21446   case X86::TCRETURNri64:
21447   case X86::TCRETURNmi64:
21448     return BB;
21449   case X86::WIN_ALLOCA:
21450     return EmitLoweredWinAlloca(MI, BB);
21451   case X86::SEG_ALLOCA_32:
21452   case X86::SEG_ALLOCA_64:
21453     return EmitLoweredSegAlloca(MI, BB);
21454   case X86::TLSCall_32:
21455   case X86::TLSCall_64:
21456     return EmitLoweredTLSCall(MI, BB);
21457   case X86::CMOV_FR32:
21458   case X86::CMOV_FR64:
21459   case X86::CMOV_GR8:
21460   case X86::CMOV_GR16:
21461   case X86::CMOV_GR32:
21462   case X86::CMOV_RFP32:
21463   case X86::CMOV_RFP64:
21464   case X86::CMOV_RFP80:
21465   case X86::CMOV_V2F64:
21466   case X86::CMOV_V2I64:
21467   case X86::CMOV_V4F32:
21468   case X86::CMOV_V4F64:
21469   case X86::CMOV_V4I64:
21470   case X86::CMOV_V16F32:
21471   case X86::CMOV_V8F32:
21472   case X86::CMOV_V8F64:
21473   case X86::CMOV_V8I64:
21474   case X86::CMOV_V8I1:
21475   case X86::CMOV_V16I1:
21476   case X86::CMOV_V32I1:
21477   case X86::CMOV_V64I1:
21478     return EmitLoweredSelect(MI, BB);
21479
21480   case X86::RELEASE_FADD32mr:
21481   case X86::RELEASE_FADD64mr:
21482     return EmitLoweredAtomicFP(MI, BB);
21483
21484   case X86::FP32_TO_INT16_IN_MEM:
21485   case X86::FP32_TO_INT32_IN_MEM:
21486   case X86::FP32_TO_INT64_IN_MEM:
21487   case X86::FP64_TO_INT16_IN_MEM:
21488   case X86::FP64_TO_INT32_IN_MEM:
21489   case X86::FP64_TO_INT64_IN_MEM:
21490   case X86::FP80_TO_INT16_IN_MEM:
21491   case X86::FP80_TO_INT32_IN_MEM:
21492   case X86::FP80_TO_INT64_IN_MEM: {
21493     MachineFunction *F = BB->getParent();
21494     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21495     DebugLoc DL = MI->getDebugLoc();
21496
21497     // Change the floating point control register to use "round towards zero"
21498     // mode when truncating to an integer value.
21499     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21500     addFrameReference(BuildMI(*BB, MI, DL,
21501                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
21502
21503     // Load the old value of the high byte of the control word...
21504     unsigned OldCW =
21505       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21506     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21507                       CWFrameIdx);
21508
21509     // Set the high part to be round to zero...
21510     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21511       .addImm(0xC7F);
21512
21513     // Reload the modified control word now...
21514     addFrameReference(BuildMI(*BB, MI, DL,
21515                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21516
21517     // Restore the memory image of control word to original value
21518     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21519       .addReg(OldCW);
21520
21521     // Get the X86 opcode to use.
21522     unsigned Opc;
21523     switch (MI->getOpcode()) {
21524     default: llvm_unreachable("illegal opcode!");
21525     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21526     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21527     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21528     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21529     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21530     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21531     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21532     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21533     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21534     }
21535
21536     X86AddressMode AM;
21537     MachineOperand &Op = MI->getOperand(0);
21538     if (Op.isReg()) {
21539       AM.BaseType = X86AddressMode::RegBase;
21540       AM.Base.Reg = Op.getReg();
21541     } else {
21542       AM.BaseType = X86AddressMode::FrameIndexBase;
21543       AM.Base.FrameIndex = Op.getIndex();
21544     }
21545     Op = MI->getOperand(1);
21546     if (Op.isImm())
21547       AM.Scale = Op.getImm();
21548     Op = MI->getOperand(2);
21549     if (Op.isImm())
21550       AM.IndexReg = Op.getImm();
21551     Op = MI->getOperand(3);
21552     if (Op.isGlobal()) {
21553       AM.GV = Op.getGlobal();
21554     } else {
21555       AM.Disp = Op.getImm();
21556     }
21557     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21558                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21559
21560     // Reload the original control word now.
21561     addFrameReference(BuildMI(*BB, MI, DL,
21562                               TII->get(X86::FLDCW16m)), CWFrameIdx);
21563
21564     MI->eraseFromParent();   // The pseudo instruction is gone now.
21565     return BB;
21566   }
21567     // String/text processing lowering.
21568   case X86::PCMPISTRM128REG:
21569   case X86::VPCMPISTRM128REG:
21570   case X86::PCMPISTRM128MEM:
21571   case X86::VPCMPISTRM128MEM:
21572   case X86::PCMPESTRM128REG:
21573   case X86::VPCMPESTRM128REG:
21574   case X86::PCMPESTRM128MEM:
21575   case X86::VPCMPESTRM128MEM:
21576     assert(Subtarget->hasSSE42() &&
21577            "Target must have SSE4.2 or AVX features enabled");
21578     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21579
21580   // String/text processing lowering.
21581   case X86::PCMPISTRIREG:
21582   case X86::VPCMPISTRIREG:
21583   case X86::PCMPISTRIMEM:
21584   case X86::VPCMPISTRIMEM:
21585   case X86::PCMPESTRIREG:
21586   case X86::VPCMPESTRIREG:
21587   case X86::PCMPESTRIMEM:
21588   case X86::VPCMPESTRIMEM:
21589     assert(Subtarget->hasSSE42() &&
21590            "Target must have SSE4.2 or AVX features enabled");
21591     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21592
21593   // Thread synchronization.
21594   case X86::MONITOR:
21595     return EmitMonitor(MI, BB, Subtarget);
21596
21597   // xbegin
21598   case X86::XBEGIN:
21599     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21600
21601   case X86::VASTART_SAVE_XMM_REGS:
21602     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21603
21604   case X86::VAARG_64:
21605     return EmitVAARG64WithCustomInserter(MI, BB);
21606
21607   case X86::EH_SjLj_SetJmp32:
21608   case X86::EH_SjLj_SetJmp64:
21609     return emitEHSjLjSetJmp(MI, BB);
21610
21611   case X86::EH_SjLj_LongJmp32:
21612   case X86::EH_SjLj_LongJmp64:
21613     return emitEHSjLjLongJmp(MI, BB);
21614
21615   case TargetOpcode::STATEPOINT:
21616     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21617     // this point in the process.  We diverge later.
21618     return emitPatchPoint(MI, BB);
21619
21620   case TargetOpcode::STACKMAP:
21621   case TargetOpcode::PATCHPOINT:
21622     return emitPatchPoint(MI, BB);
21623
21624   case X86::VFMADDPDr213r:
21625   case X86::VFMADDPSr213r:
21626   case X86::VFMADDSDr213r:
21627   case X86::VFMADDSSr213r:
21628   case X86::VFMSUBPDr213r:
21629   case X86::VFMSUBPSr213r:
21630   case X86::VFMSUBSDr213r:
21631   case X86::VFMSUBSSr213r:
21632   case X86::VFNMADDPDr213r:
21633   case X86::VFNMADDPSr213r:
21634   case X86::VFNMADDSDr213r:
21635   case X86::VFNMADDSSr213r:
21636   case X86::VFNMSUBPDr213r:
21637   case X86::VFNMSUBPSr213r:
21638   case X86::VFNMSUBSDr213r:
21639   case X86::VFNMSUBSSr213r:
21640   case X86::VFMADDSUBPDr213r:
21641   case X86::VFMADDSUBPSr213r:
21642   case X86::VFMSUBADDPDr213r:
21643   case X86::VFMSUBADDPSr213r:
21644   case X86::VFMADDPDr213rY:
21645   case X86::VFMADDPSr213rY:
21646   case X86::VFMSUBPDr213rY:
21647   case X86::VFMSUBPSr213rY:
21648   case X86::VFNMADDPDr213rY:
21649   case X86::VFNMADDPSr213rY:
21650   case X86::VFNMSUBPDr213rY:
21651   case X86::VFNMSUBPSr213rY:
21652   case X86::VFMADDSUBPDr213rY:
21653   case X86::VFMADDSUBPSr213rY:
21654   case X86::VFMSUBADDPDr213rY:
21655   case X86::VFMSUBADDPSr213rY:
21656     return emitFMA3Instr(MI, BB);
21657   }
21658 }
21659
21660 //===----------------------------------------------------------------------===//
21661 //                           X86 Optimization Hooks
21662 //===----------------------------------------------------------------------===//
21663
21664 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21665                                                       APInt &KnownZero,
21666                                                       APInt &KnownOne,
21667                                                       const SelectionDAG &DAG,
21668                                                       unsigned Depth) const {
21669   unsigned BitWidth = KnownZero.getBitWidth();
21670   unsigned Opc = Op.getOpcode();
21671   assert((Opc >= ISD::BUILTIN_OP_END ||
21672           Opc == ISD::INTRINSIC_WO_CHAIN ||
21673           Opc == ISD::INTRINSIC_W_CHAIN ||
21674           Opc == ISD::INTRINSIC_VOID) &&
21675          "Should use MaskedValueIsZero if you don't know whether Op"
21676          " is a target node!");
21677
21678   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21679   switch (Opc) {
21680   default: break;
21681   case X86ISD::ADD:
21682   case X86ISD::SUB:
21683   case X86ISD::ADC:
21684   case X86ISD::SBB:
21685   case X86ISD::SMUL:
21686   case X86ISD::UMUL:
21687   case X86ISD::INC:
21688   case X86ISD::DEC:
21689   case X86ISD::OR:
21690   case X86ISD::XOR:
21691   case X86ISD::AND:
21692     // These nodes' second result is a boolean.
21693     if (Op.getResNo() == 0)
21694       break;
21695     // Fallthrough
21696   case X86ISD::SETCC:
21697     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21698     break;
21699   case ISD::INTRINSIC_WO_CHAIN: {
21700     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21701     unsigned NumLoBits = 0;
21702     switch (IntId) {
21703     default: break;
21704     case Intrinsic::x86_sse_movmsk_ps:
21705     case Intrinsic::x86_avx_movmsk_ps_256:
21706     case Intrinsic::x86_sse2_movmsk_pd:
21707     case Intrinsic::x86_avx_movmsk_pd_256:
21708     case Intrinsic::x86_mmx_pmovmskb:
21709     case Intrinsic::x86_sse2_pmovmskb_128:
21710     case Intrinsic::x86_avx2_pmovmskb: {
21711       // High bits of movmskp{s|d}, pmovmskb are known zero.
21712       switch (IntId) {
21713         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21714         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21715         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21716         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21717         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21718         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21719         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21720         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21721       }
21722       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21723       break;
21724     }
21725     }
21726     break;
21727   }
21728   }
21729 }
21730
21731 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21732   SDValue Op,
21733   const SelectionDAG &,
21734   unsigned Depth) const {
21735   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21736   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21737     return Op.getValueType().getScalarType().getSizeInBits();
21738
21739   // Fallback case.
21740   return 1;
21741 }
21742
21743 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21744 /// node is a GlobalAddress + offset.
21745 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21746                                        const GlobalValue* &GA,
21747                                        int64_t &Offset) const {
21748   if (N->getOpcode() == X86ISD::Wrapper) {
21749     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21750       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21751       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21752       return true;
21753     }
21754   }
21755   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21756 }
21757
21758 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21759 /// same as extracting the high 128-bit part of 256-bit vector and then
21760 /// inserting the result into the low part of a new 256-bit vector
21761 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21762   EVT VT = SVOp->getValueType(0);
21763   unsigned NumElems = VT.getVectorNumElements();
21764
21765   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21766   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21767     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21768         SVOp->getMaskElt(j) >= 0)
21769       return false;
21770
21771   return true;
21772 }
21773
21774 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21775 /// same as extracting the low 128-bit part of 256-bit vector and then
21776 /// inserting the result into the high part of a new 256-bit vector
21777 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21778   EVT VT = SVOp->getValueType(0);
21779   unsigned NumElems = VT.getVectorNumElements();
21780
21781   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21782   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21783     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21784         SVOp->getMaskElt(j) >= 0)
21785       return false;
21786
21787   return true;
21788 }
21789
21790 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21791 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21792                                         TargetLowering::DAGCombinerInfo &DCI,
21793                                         const X86Subtarget* Subtarget) {
21794   SDLoc dl(N);
21795   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21796   SDValue V1 = SVOp->getOperand(0);
21797   SDValue V2 = SVOp->getOperand(1);
21798   EVT VT = SVOp->getValueType(0);
21799   unsigned NumElems = VT.getVectorNumElements();
21800
21801   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21802       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21803     //
21804     //                   0,0,0,...
21805     //                      |
21806     //    V      UNDEF    BUILD_VECTOR    UNDEF
21807     //     \      /           \           /
21808     //  CONCAT_VECTOR         CONCAT_VECTOR
21809     //         \                  /
21810     //          \                /
21811     //          RESULT: V + zero extended
21812     //
21813     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21814         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21815         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21816       return SDValue();
21817
21818     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21819       return SDValue();
21820
21821     // To match the shuffle mask, the first half of the mask should
21822     // be exactly the first vector, and all the rest a splat with the
21823     // first element of the second one.
21824     for (unsigned i = 0; i != NumElems/2; ++i)
21825       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21826           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21827         return SDValue();
21828
21829     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21830     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21831       if (Ld->hasNUsesOfValue(1, 0)) {
21832         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21833         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21834         SDValue ResNode =
21835           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21836                                   Ld->getMemoryVT(),
21837                                   Ld->getPointerInfo(),
21838                                   Ld->getAlignment(),
21839                                   false/*isVolatile*/, true/*ReadMem*/,
21840                                   false/*WriteMem*/);
21841
21842         // Make sure the newly-created LOAD is in the same position as Ld in
21843         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21844         // and update uses of Ld's output chain to use the TokenFactor.
21845         if (Ld->hasAnyUseOfValue(1)) {
21846           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21847                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21848           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21849           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21850                                  SDValue(ResNode.getNode(), 1));
21851         }
21852
21853         return DAG.getBitcast(VT, ResNode);
21854       }
21855     }
21856
21857     // Emit a zeroed vector and insert the desired subvector on its
21858     // first half.
21859     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21860     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21861     return DCI.CombineTo(N, InsV);
21862   }
21863
21864   //===--------------------------------------------------------------------===//
21865   // Combine some shuffles into subvector extracts and inserts:
21866   //
21867
21868   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21869   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21870     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21871     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21872     return DCI.CombineTo(N, InsV);
21873   }
21874
21875   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21876   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21877     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21878     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21879     return DCI.CombineTo(N, InsV);
21880   }
21881
21882   return SDValue();
21883 }
21884
21885 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21886 /// possible.
21887 ///
21888 /// This is the leaf of the recursive combinine below. When we have found some
21889 /// chain of single-use x86 shuffle instructions and accumulated the combined
21890 /// shuffle mask represented by them, this will try to pattern match that mask
21891 /// into either a single instruction if there is a special purpose instruction
21892 /// for this operation, or into a PSHUFB instruction which is a fully general
21893 /// instruction but should only be used to replace chains over a certain depth.
21894 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21895                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21896                                    TargetLowering::DAGCombinerInfo &DCI,
21897                                    const X86Subtarget *Subtarget) {
21898   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21899
21900   // Find the operand that enters the chain. Note that multiple uses are OK
21901   // here, we're not going to remove the operand we find.
21902   SDValue Input = Op.getOperand(0);
21903   while (Input.getOpcode() == ISD::BITCAST)
21904     Input = Input.getOperand(0);
21905
21906   MVT VT = Input.getSimpleValueType();
21907   MVT RootVT = Root.getSimpleValueType();
21908   SDLoc DL(Root);
21909
21910   // Just remove no-op shuffle masks.
21911   if (Mask.size() == 1) {
21912     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21913                   /*AddTo*/ true);
21914     return true;
21915   }
21916
21917   // Use the float domain if the operand type is a floating point type.
21918   bool FloatDomain = VT.isFloatingPoint();
21919
21920   // For floating point shuffles, we don't have free copies in the shuffle
21921   // instructions or the ability to load as part of the instruction, so
21922   // canonicalize their shuffles to UNPCK or MOV variants.
21923   //
21924   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21925   // vectors because it can have a load folded into it that UNPCK cannot. This
21926   // doesn't preclude something switching to the shorter encoding post-RA.
21927   //
21928   // FIXME: Should teach these routines about AVX vector widths.
21929   if (FloatDomain && VT.getSizeInBits() == 128) {
21930     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21931       bool Lo = Mask.equals({0, 0});
21932       unsigned Shuffle;
21933       MVT ShuffleVT;
21934       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21935       // is no slower than UNPCKLPD but has the option to fold the input operand
21936       // into even an unaligned memory load.
21937       if (Lo && Subtarget->hasSSE3()) {
21938         Shuffle = X86ISD::MOVDDUP;
21939         ShuffleVT = MVT::v2f64;
21940       } else {
21941         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21942         // than the UNPCK variants.
21943         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21944         ShuffleVT = MVT::v4f32;
21945       }
21946       if (Depth == 1 && Root->getOpcode() == Shuffle)
21947         return false; // Nothing to do!
21948       Op = DAG.getBitcast(ShuffleVT, Input);
21949       DCI.AddToWorklist(Op.getNode());
21950       if (Shuffle == X86ISD::MOVDDUP)
21951         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21952       else
21953         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21954       DCI.AddToWorklist(Op.getNode());
21955       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21956                     /*AddTo*/ true);
21957       return true;
21958     }
21959     if (Subtarget->hasSSE3() &&
21960         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21961       bool Lo = Mask.equals({0, 0, 2, 2});
21962       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21963       MVT ShuffleVT = MVT::v4f32;
21964       if (Depth == 1 && Root->getOpcode() == Shuffle)
21965         return false; // Nothing to do!
21966       Op = DAG.getBitcast(ShuffleVT, Input);
21967       DCI.AddToWorklist(Op.getNode());
21968       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21969       DCI.AddToWorklist(Op.getNode());
21970       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21971                     /*AddTo*/ true);
21972       return true;
21973     }
21974     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21975       bool Lo = Mask.equals({0, 0, 1, 1});
21976       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21977       MVT ShuffleVT = MVT::v4f32;
21978       if (Depth == 1 && Root->getOpcode() == Shuffle)
21979         return false; // Nothing to do!
21980       Op = DAG.getBitcast(ShuffleVT, Input);
21981       DCI.AddToWorklist(Op.getNode());
21982       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21983       DCI.AddToWorklist(Op.getNode());
21984       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21985                     /*AddTo*/ true);
21986       return true;
21987     }
21988   }
21989
21990   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21991   // variants as none of these have single-instruction variants that are
21992   // superior to the UNPCK formulation.
21993   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21994       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21995        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21996        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21997        Mask.equals(
21998            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21999     bool Lo = Mask[0] == 0;
22000     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22001     if (Depth == 1 && Root->getOpcode() == Shuffle)
22002       return false; // Nothing to do!
22003     MVT ShuffleVT;
22004     switch (Mask.size()) {
22005     case 8:
22006       ShuffleVT = MVT::v8i16;
22007       break;
22008     case 16:
22009       ShuffleVT = MVT::v16i8;
22010       break;
22011     default:
22012       llvm_unreachable("Impossible mask size!");
22013     };
22014     Op = DAG.getBitcast(ShuffleVT, Input);
22015     DCI.AddToWorklist(Op.getNode());
22016     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22017     DCI.AddToWorklist(Op.getNode());
22018     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22019                   /*AddTo*/ true);
22020     return true;
22021   }
22022
22023   // Don't try to re-form single instruction chains under any circumstances now
22024   // that we've done encoding canonicalization for them.
22025   if (Depth < 2)
22026     return false;
22027
22028   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22029   // can replace them with a single PSHUFB instruction profitably. Intel's
22030   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22031   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22032   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22033     SmallVector<SDValue, 16> PSHUFBMask;
22034     int NumBytes = VT.getSizeInBits() / 8;
22035     int Ratio = NumBytes / Mask.size();
22036     for (int i = 0; i < NumBytes; ++i) {
22037       if (Mask[i / Ratio] == SM_SentinelUndef) {
22038         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22039         continue;
22040       }
22041       int M = Mask[i / Ratio] != SM_SentinelZero
22042                   ? Ratio * Mask[i / Ratio] + i % Ratio
22043                   : 255;
22044       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22045     }
22046     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22047     Op = DAG.getBitcast(ByteVT, Input);
22048     DCI.AddToWorklist(Op.getNode());
22049     SDValue PSHUFBMaskOp =
22050         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22051     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22052     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22053     DCI.AddToWorklist(Op.getNode());
22054     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22055                   /*AddTo*/ true);
22056     return true;
22057   }
22058
22059   // Failed to find any combines.
22060   return false;
22061 }
22062
22063 /// \brief Fully generic combining of x86 shuffle instructions.
22064 ///
22065 /// This should be the last combine run over the x86 shuffle instructions. Once
22066 /// they have been fully optimized, this will recursively consider all chains
22067 /// of single-use shuffle instructions, build a generic model of the cumulative
22068 /// shuffle operation, and check for simpler instructions which implement this
22069 /// operation. We use this primarily for two purposes:
22070 ///
22071 /// 1) Collapse generic shuffles to specialized single instructions when
22072 ///    equivalent. In most cases, this is just an encoding size win, but
22073 ///    sometimes we will collapse multiple generic shuffles into a single
22074 ///    special-purpose shuffle.
22075 /// 2) Look for sequences of shuffle instructions with 3 or more total
22076 ///    instructions, and replace them with the slightly more expensive SSSE3
22077 ///    PSHUFB instruction if available. We do this as the last combining step
22078 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22079 ///    a suitable short sequence of other instructions. The PHUFB will either
22080 ///    use a register or have to read from memory and so is slightly (but only
22081 ///    slightly) more expensive than the other shuffle instructions.
22082 ///
22083 /// Because this is inherently a quadratic operation (for each shuffle in
22084 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22085 /// This should never be an issue in practice as the shuffle lowering doesn't
22086 /// produce sequences of more than 8 instructions.
22087 ///
22088 /// FIXME: We will currently miss some cases where the redundant shuffling
22089 /// would simplify under the threshold for PSHUFB formation because of
22090 /// combine-ordering. To fix this, we should do the redundant instruction
22091 /// combining in this recursive walk.
22092 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22093                                           ArrayRef<int> RootMask,
22094                                           int Depth, bool HasPSHUFB,
22095                                           SelectionDAG &DAG,
22096                                           TargetLowering::DAGCombinerInfo &DCI,
22097                                           const X86Subtarget *Subtarget) {
22098   // Bound the depth of our recursive combine because this is ultimately
22099   // quadratic in nature.
22100   if (Depth > 8)
22101     return false;
22102
22103   // Directly rip through bitcasts to find the underlying operand.
22104   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22105     Op = Op.getOperand(0);
22106
22107   MVT VT = Op.getSimpleValueType();
22108   if (!VT.isVector())
22109     return false; // Bail if we hit a non-vector.
22110
22111   assert(Root.getSimpleValueType().isVector() &&
22112          "Shuffles operate on vector types!");
22113   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22114          "Can only combine shuffles of the same vector register size.");
22115
22116   if (!isTargetShuffle(Op.getOpcode()))
22117     return false;
22118   SmallVector<int, 16> OpMask;
22119   bool IsUnary;
22120   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22121   // We only can combine unary shuffles which we can decode the mask for.
22122   if (!HaveMask || !IsUnary)
22123     return false;
22124
22125   assert(VT.getVectorNumElements() == OpMask.size() &&
22126          "Different mask size from vector size!");
22127   assert(((RootMask.size() > OpMask.size() &&
22128            RootMask.size() % OpMask.size() == 0) ||
22129           (OpMask.size() > RootMask.size() &&
22130            OpMask.size() % RootMask.size() == 0) ||
22131           OpMask.size() == RootMask.size()) &&
22132          "The smaller number of elements must divide the larger.");
22133   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22134   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22135   assert(((RootRatio == 1 && OpRatio == 1) ||
22136           (RootRatio == 1) != (OpRatio == 1)) &&
22137          "Must not have a ratio for both incoming and op masks!");
22138
22139   SmallVector<int, 16> Mask;
22140   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22141
22142   // Merge this shuffle operation's mask into our accumulated mask. Note that
22143   // this shuffle's mask will be the first applied to the input, followed by the
22144   // root mask to get us all the way to the root value arrangement. The reason
22145   // for this order is that we are recursing up the operation chain.
22146   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22147     int RootIdx = i / RootRatio;
22148     if (RootMask[RootIdx] < 0) {
22149       // This is a zero or undef lane, we're done.
22150       Mask.push_back(RootMask[RootIdx]);
22151       continue;
22152     }
22153
22154     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22155     int OpIdx = RootMaskedIdx / OpRatio;
22156     if (OpMask[OpIdx] < 0) {
22157       // The incoming lanes are zero or undef, it doesn't matter which ones we
22158       // are using.
22159       Mask.push_back(OpMask[OpIdx]);
22160       continue;
22161     }
22162
22163     // Ok, we have non-zero lanes, map them through.
22164     Mask.push_back(OpMask[OpIdx] * OpRatio +
22165                    RootMaskedIdx % OpRatio);
22166   }
22167
22168   // See if we can recurse into the operand to combine more things.
22169   switch (Op.getOpcode()) {
22170   case X86ISD::PSHUFB:
22171     HasPSHUFB = true;
22172   case X86ISD::PSHUFD:
22173   case X86ISD::PSHUFHW:
22174   case X86ISD::PSHUFLW:
22175     if (Op.getOperand(0).hasOneUse() &&
22176         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22177                                       HasPSHUFB, DAG, DCI, Subtarget))
22178       return true;
22179     break;
22180
22181   case X86ISD::UNPCKL:
22182   case X86ISD::UNPCKH:
22183     assert(Op.getOperand(0) == Op.getOperand(1) &&
22184            "We only combine unary shuffles!");
22185     // We can't check for single use, we have to check that this shuffle is the
22186     // only user.
22187     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22188         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22189                                       HasPSHUFB, DAG, DCI, Subtarget))
22190       return true;
22191     break;
22192   }
22193
22194   // Minor canonicalization of the accumulated shuffle mask to make it easier
22195   // to match below. All this does is detect masks with squential pairs of
22196   // elements, and shrink them to the half-width mask. It does this in a loop
22197   // so it will reduce the size of the mask to the minimal width mask which
22198   // performs an equivalent shuffle.
22199   SmallVector<int, 16> WidenedMask;
22200   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22201     Mask = std::move(WidenedMask);
22202     WidenedMask.clear();
22203   }
22204
22205   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22206                                 Subtarget);
22207 }
22208
22209 /// \brief Get the PSHUF-style mask from PSHUF node.
22210 ///
22211 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22212 /// PSHUF-style masks that can be reused with such instructions.
22213 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22214   MVT VT = N.getSimpleValueType();
22215   SmallVector<int, 4> Mask;
22216   bool IsUnary;
22217   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22218   (void)HaveMask;
22219   assert(HaveMask);
22220
22221   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22222   // matter. Check that the upper masks are repeats and remove them.
22223   if (VT.getSizeInBits() > 128) {
22224     int LaneElts = 128 / VT.getScalarSizeInBits();
22225 #ifndef NDEBUG
22226     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22227       for (int j = 0; j < LaneElts; ++j)
22228         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22229                "Mask doesn't repeat in high 128-bit lanes!");
22230 #endif
22231     Mask.resize(LaneElts);
22232   }
22233
22234   switch (N.getOpcode()) {
22235   case X86ISD::PSHUFD:
22236     return Mask;
22237   case X86ISD::PSHUFLW:
22238     Mask.resize(4);
22239     return Mask;
22240   case X86ISD::PSHUFHW:
22241     Mask.erase(Mask.begin(), Mask.begin() + 4);
22242     for (int &M : Mask)
22243       M -= 4;
22244     return Mask;
22245   default:
22246     llvm_unreachable("No valid shuffle instruction found!");
22247   }
22248 }
22249
22250 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22251 ///
22252 /// We walk up the chain and look for a combinable shuffle, skipping over
22253 /// shuffles that we could hoist this shuffle's transformation past without
22254 /// altering anything.
22255 static SDValue
22256 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22257                              SelectionDAG &DAG,
22258                              TargetLowering::DAGCombinerInfo &DCI) {
22259   assert(N.getOpcode() == X86ISD::PSHUFD &&
22260          "Called with something other than an x86 128-bit half shuffle!");
22261   SDLoc DL(N);
22262
22263   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22264   // of the shuffles in the chain so that we can form a fresh chain to replace
22265   // this one.
22266   SmallVector<SDValue, 8> Chain;
22267   SDValue V = N.getOperand(0);
22268   for (; V.hasOneUse(); V = V.getOperand(0)) {
22269     switch (V.getOpcode()) {
22270     default:
22271       return SDValue(); // Nothing combined!
22272
22273     case ISD::BITCAST:
22274       // Skip bitcasts as we always know the type for the target specific
22275       // instructions.
22276       continue;
22277
22278     case X86ISD::PSHUFD:
22279       // Found another dword shuffle.
22280       break;
22281
22282     case X86ISD::PSHUFLW:
22283       // Check that the low words (being shuffled) are the identity in the
22284       // dword shuffle, and the high words are self-contained.
22285       if (Mask[0] != 0 || Mask[1] != 1 ||
22286           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22287         return SDValue();
22288
22289       Chain.push_back(V);
22290       continue;
22291
22292     case X86ISD::PSHUFHW:
22293       // Check that the high words (being shuffled) are the identity in the
22294       // dword shuffle, and the low words are self-contained.
22295       if (Mask[2] != 2 || Mask[3] != 3 ||
22296           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22297         return SDValue();
22298
22299       Chain.push_back(V);
22300       continue;
22301
22302     case X86ISD::UNPCKL:
22303     case X86ISD::UNPCKH:
22304       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22305       // shuffle into a preceding word shuffle.
22306       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22307           V.getSimpleValueType().getScalarType() != MVT::i16)
22308         return SDValue();
22309
22310       // Search for a half-shuffle which we can combine with.
22311       unsigned CombineOp =
22312           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22313       if (V.getOperand(0) != V.getOperand(1) ||
22314           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22315         return SDValue();
22316       Chain.push_back(V);
22317       V = V.getOperand(0);
22318       do {
22319         switch (V.getOpcode()) {
22320         default:
22321           return SDValue(); // Nothing to combine.
22322
22323         case X86ISD::PSHUFLW:
22324         case X86ISD::PSHUFHW:
22325           if (V.getOpcode() == CombineOp)
22326             break;
22327
22328           Chain.push_back(V);
22329
22330           // Fallthrough!
22331         case ISD::BITCAST:
22332           V = V.getOperand(0);
22333           continue;
22334         }
22335         break;
22336       } while (V.hasOneUse());
22337       break;
22338     }
22339     // Break out of the loop if we break out of the switch.
22340     break;
22341   }
22342
22343   if (!V.hasOneUse())
22344     // We fell out of the loop without finding a viable combining instruction.
22345     return SDValue();
22346
22347   // Merge this node's mask and our incoming mask.
22348   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22349   for (int &M : Mask)
22350     M = VMask[M];
22351   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22352                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22353
22354   // Rebuild the chain around this new shuffle.
22355   while (!Chain.empty()) {
22356     SDValue W = Chain.pop_back_val();
22357
22358     if (V.getValueType() != W.getOperand(0).getValueType())
22359       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22360
22361     switch (W.getOpcode()) {
22362     default:
22363       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22364
22365     case X86ISD::UNPCKL:
22366     case X86ISD::UNPCKH:
22367       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22368       break;
22369
22370     case X86ISD::PSHUFD:
22371     case X86ISD::PSHUFLW:
22372     case X86ISD::PSHUFHW:
22373       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22374       break;
22375     }
22376   }
22377   if (V.getValueType() != N.getValueType())
22378     V = DAG.getBitcast(N.getValueType(), V);
22379
22380   // Return the new chain to replace N.
22381   return V;
22382 }
22383
22384 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22385 /// pshufhw.
22386 ///
22387 /// We walk up the chain, skipping shuffles of the other half and looking
22388 /// through shuffles which switch halves trying to find a shuffle of the same
22389 /// pair of dwords.
22390 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22391                                         SelectionDAG &DAG,
22392                                         TargetLowering::DAGCombinerInfo &DCI) {
22393   assert(
22394       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22395       "Called with something other than an x86 128-bit half shuffle!");
22396   SDLoc DL(N);
22397   unsigned CombineOpcode = N.getOpcode();
22398
22399   // Walk up a single-use chain looking for a combinable shuffle.
22400   SDValue V = N.getOperand(0);
22401   for (; V.hasOneUse(); V = V.getOperand(0)) {
22402     switch (V.getOpcode()) {
22403     default:
22404       return false; // Nothing combined!
22405
22406     case ISD::BITCAST:
22407       // Skip bitcasts as we always know the type for the target specific
22408       // instructions.
22409       continue;
22410
22411     case X86ISD::PSHUFLW:
22412     case X86ISD::PSHUFHW:
22413       if (V.getOpcode() == CombineOpcode)
22414         break;
22415
22416       // Other-half shuffles are no-ops.
22417       continue;
22418     }
22419     // Break out of the loop if we break out of the switch.
22420     break;
22421   }
22422
22423   if (!V.hasOneUse())
22424     // We fell out of the loop without finding a viable combining instruction.
22425     return false;
22426
22427   // Combine away the bottom node as its shuffle will be accumulated into
22428   // a preceding shuffle.
22429   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22430
22431   // Record the old value.
22432   SDValue Old = V;
22433
22434   // Merge this node's mask and our incoming mask (adjusted to account for all
22435   // the pshufd instructions encountered).
22436   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22437   for (int &M : Mask)
22438     M = VMask[M];
22439   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22440                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22441
22442   // Check that the shuffles didn't cancel each other out. If not, we need to
22443   // combine to the new one.
22444   if (Old != V)
22445     // Replace the combinable shuffle with the combined one, updating all users
22446     // so that we re-evaluate the chain here.
22447     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22448
22449   return true;
22450 }
22451
22452 /// \brief Try to combine x86 target specific shuffles.
22453 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22454                                            TargetLowering::DAGCombinerInfo &DCI,
22455                                            const X86Subtarget *Subtarget) {
22456   SDLoc DL(N);
22457   MVT VT = N.getSimpleValueType();
22458   SmallVector<int, 4> Mask;
22459
22460   switch (N.getOpcode()) {
22461   case X86ISD::PSHUFD:
22462   case X86ISD::PSHUFLW:
22463   case X86ISD::PSHUFHW:
22464     Mask = getPSHUFShuffleMask(N);
22465     assert(Mask.size() == 4);
22466     break;
22467   default:
22468     return SDValue();
22469   }
22470
22471   // Nuke no-op shuffles that show up after combining.
22472   if (isNoopShuffleMask(Mask))
22473     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22474
22475   // Look for simplifications involving one or two shuffle instructions.
22476   SDValue V = N.getOperand(0);
22477   switch (N.getOpcode()) {
22478   default:
22479     break;
22480   case X86ISD::PSHUFLW:
22481   case X86ISD::PSHUFHW:
22482     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22483
22484     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22485       return SDValue(); // We combined away this shuffle, so we're done.
22486
22487     // See if this reduces to a PSHUFD which is no more expensive and can
22488     // combine with more operations. Note that it has to at least flip the
22489     // dwords as otherwise it would have been removed as a no-op.
22490     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22491       int DMask[] = {0, 1, 2, 3};
22492       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22493       DMask[DOffset + 0] = DOffset + 1;
22494       DMask[DOffset + 1] = DOffset + 0;
22495       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22496       V = DAG.getBitcast(DVT, V);
22497       DCI.AddToWorklist(V.getNode());
22498       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22499                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22500       DCI.AddToWorklist(V.getNode());
22501       return DAG.getBitcast(VT, V);
22502     }
22503
22504     // Look for shuffle patterns which can be implemented as a single unpack.
22505     // FIXME: This doesn't handle the location of the PSHUFD generically, and
22506     // only works when we have a PSHUFD followed by two half-shuffles.
22507     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22508         (V.getOpcode() == X86ISD::PSHUFLW ||
22509          V.getOpcode() == X86ISD::PSHUFHW) &&
22510         V.getOpcode() != N.getOpcode() &&
22511         V.hasOneUse()) {
22512       SDValue D = V.getOperand(0);
22513       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22514         D = D.getOperand(0);
22515       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22516         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22517         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22518         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22519         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22520         int WordMask[8];
22521         for (int i = 0; i < 4; ++i) {
22522           WordMask[i + NOffset] = Mask[i] + NOffset;
22523           WordMask[i + VOffset] = VMask[i] + VOffset;
22524         }
22525         // Map the word mask through the DWord mask.
22526         int MappedMask[8];
22527         for (int i = 0; i < 8; ++i)
22528           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22529         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22530             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22531           // We can replace all three shuffles with an unpack.
22532           V = DAG.getBitcast(VT, D.getOperand(0));
22533           DCI.AddToWorklist(V.getNode());
22534           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22535                                                 : X86ISD::UNPCKH,
22536                              DL, VT, V, V);
22537         }
22538       }
22539     }
22540
22541     break;
22542
22543   case X86ISD::PSHUFD:
22544     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22545       return NewN;
22546
22547     break;
22548   }
22549
22550   return SDValue();
22551 }
22552
22553 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22554 ///
22555 /// We combine this directly on the abstract vector shuffle nodes so it is
22556 /// easier to generically match. We also insert dummy vector shuffle nodes for
22557 /// the operands which explicitly discard the lanes which are unused by this
22558 /// operation to try to flow through the rest of the combiner the fact that
22559 /// they're unused.
22560 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22561   SDLoc DL(N);
22562   EVT VT = N->getValueType(0);
22563
22564   // We only handle target-independent shuffles.
22565   // FIXME: It would be easy and harmless to use the target shuffle mask
22566   // extraction tool to support more.
22567   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22568     return SDValue();
22569
22570   auto *SVN = cast<ShuffleVectorSDNode>(N);
22571   ArrayRef<int> Mask = SVN->getMask();
22572   SDValue V1 = N->getOperand(0);
22573   SDValue V2 = N->getOperand(1);
22574
22575   // We require the first shuffle operand to be the SUB node, and the second to
22576   // be the ADD node.
22577   // FIXME: We should support the commuted patterns.
22578   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22579     return SDValue();
22580
22581   // If there are other uses of these operations we can't fold them.
22582   if (!V1->hasOneUse() || !V2->hasOneUse())
22583     return SDValue();
22584
22585   // Ensure that both operations have the same operands. Note that we can
22586   // commute the FADD operands.
22587   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22588   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22589       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22590     return SDValue();
22591
22592   // We're looking for blends between FADD and FSUB nodes. We insist on these
22593   // nodes being lined up in a specific expected pattern.
22594   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22595         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22596         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22597     return SDValue();
22598
22599   // Only specific types are legal at this point, assert so we notice if and
22600   // when these change.
22601   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22602           VT == MVT::v4f64) &&
22603          "Unknown vector type encountered!");
22604
22605   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22606 }
22607
22608 /// PerformShuffleCombine - Performs several different shuffle combines.
22609 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22610                                      TargetLowering::DAGCombinerInfo &DCI,
22611                                      const X86Subtarget *Subtarget) {
22612   SDLoc dl(N);
22613   SDValue N0 = N->getOperand(0);
22614   SDValue N1 = N->getOperand(1);
22615   EVT VT = N->getValueType(0);
22616
22617   // Don't create instructions with illegal types after legalize types has run.
22618   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22619   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22620     return SDValue();
22621
22622   // If we have legalized the vector types, look for blends of FADD and FSUB
22623   // nodes that we can fuse into an ADDSUB node.
22624   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22625     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22626       return AddSub;
22627
22628   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22629   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22630       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22631     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22632
22633   // During Type Legalization, when promoting illegal vector types,
22634   // the backend might introduce new shuffle dag nodes and bitcasts.
22635   //
22636   // This code performs the following transformation:
22637   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22638   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22639   //
22640   // We do this only if both the bitcast and the BINOP dag nodes have
22641   // one use. Also, perform this transformation only if the new binary
22642   // operation is legal. This is to avoid introducing dag nodes that
22643   // potentially need to be further expanded (or custom lowered) into a
22644   // less optimal sequence of dag nodes.
22645   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22646       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22647       N0.getOpcode() == ISD::BITCAST) {
22648     SDValue BC0 = N0.getOperand(0);
22649     EVT SVT = BC0.getValueType();
22650     unsigned Opcode = BC0.getOpcode();
22651     unsigned NumElts = VT.getVectorNumElements();
22652
22653     if (BC0.hasOneUse() && SVT.isVector() &&
22654         SVT.getVectorNumElements() * 2 == NumElts &&
22655         TLI.isOperationLegal(Opcode, VT)) {
22656       bool CanFold = false;
22657       switch (Opcode) {
22658       default : break;
22659       case ISD::ADD :
22660       case ISD::FADD :
22661       case ISD::SUB :
22662       case ISD::FSUB :
22663       case ISD::MUL :
22664       case ISD::FMUL :
22665         CanFold = true;
22666       }
22667
22668       unsigned SVTNumElts = SVT.getVectorNumElements();
22669       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22670       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22671         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22672       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22673         CanFold = SVOp->getMaskElt(i) < 0;
22674
22675       if (CanFold) {
22676         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22677         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22678         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22679         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22680       }
22681     }
22682   }
22683
22684   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22685   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22686   // consecutive, non-overlapping, and in the right order.
22687   SmallVector<SDValue, 16> Elts;
22688   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22689     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22690
22691   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22692     return LD;
22693
22694   if (isTargetShuffle(N->getOpcode())) {
22695     SDValue Shuffle =
22696         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22697     if (Shuffle.getNode())
22698       return Shuffle;
22699
22700     // Try recursively combining arbitrary sequences of x86 shuffle
22701     // instructions into higher-order shuffles. We do this after combining
22702     // specific PSHUF instruction sequences into their minimal form so that we
22703     // can evaluate how many specialized shuffle instructions are involved in
22704     // a particular chain.
22705     SmallVector<int, 1> NonceMask; // Just a placeholder.
22706     NonceMask.push_back(0);
22707     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22708                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22709                                       DCI, Subtarget))
22710       return SDValue(); // This routine will use CombineTo to replace N.
22711   }
22712
22713   return SDValue();
22714 }
22715
22716 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22717 /// specific shuffle of a load can be folded into a single element load.
22718 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22719 /// shuffles have been custom lowered so we need to handle those here.
22720 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22721                                          TargetLowering::DAGCombinerInfo &DCI) {
22722   if (DCI.isBeforeLegalizeOps())
22723     return SDValue();
22724
22725   SDValue InVec = N->getOperand(0);
22726   SDValue EltNo = N->getOperand(1);
22727
22728   if (!isa<ConstantSDNode>(EltNo))
22729     return SDValue();
22730
22731   EVT OriginalVT = InVec.getValueType();
22732
22733   if (InVec.getOpcode() == ISD::BITCAST) {
22734     // Don't duplicate a load with other uses.
22735     if (!InVec.hasOneUse())
22736       return SDValue();
22737     EVT BCVT = InVec.getOperand(0).getValueType();
22738     if (!BCVT.isVector() ||
22739         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22740       return SDValue();
22741     InVec = InVec.getOperand(0);
22742   }
22743
22744   EVT CurrentVT = InVec.getValueType();
22745
22746   if (!isTargetShuffle(InVec.getOpcode()))
22747     return SDValue();
22748
22749   // Don't duplicate a load with other uses.
22750   if (!InVec.hasOneUse())
22751     return SDValue();
22752
22753   SmallVector<int, 16> ShuffleMask;
22754   bool UnaryShuffle;
22755   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22756                             ShuffleMask, UnaryShuffle))
22757     return SDValue();
22758
22759   // Select the input vector, guarding against out of range extract vector.
22760   unsigned NumElems = CurrentVT.getVectorNumElements();
22761   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22762   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22763   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22764                                          : InVec.getOperand(1);
22765
22766   // If inputs to shuffle are the same for both ops, then allow 2 uses
22767   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22768                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22769
22770   if (LdNode.getOpcode() == ISD::BITCAST) {
22771     // Don't duplicate a load with other uses.
22772     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22773       return SDValue();
22774
22775     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22776     LdNode = LdNode.getOperand(0);
22777   }
22778
22779   if (!ISD::isNormalLoad(LdNode.getNode()))
22780     return SDValue();
22781
22782   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22783
22784   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22785     return SDValue();
22786
22787   EVT EltVT = N->getValueType(0);
22788   // If there's a bitcast before the shuffle, check if the load type and
22789   // alignment is valid.
22790   unsigned Align = LN0->getAlignment();
22791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22792   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22793       EltVT.getTypeForEVT(*DAG.getContext()));
22794
22795   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22796     return SDValue();
22797
22798   // All checks match so transform back to vector_shuffle so that DAG combiner
22799   // can finish the job
22800   SDLoc dl(N);
22801
22802   // Create shuffle node taking into account the case that its a unary shuffle
22803   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22804                                    : InVec.getOperand(1);
22805   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22806                                  InVec.getOperand(0), Shuffle,
22807                                  &ShuffleMask[0]);
22808   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22809   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22810                      EltNo);
22811 }
22812
22813 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22814 /// special and don't usually play with other vector types, it's better to
22815 /// handle them early to be sure we emit efficient code by avoiding
22816 /// store-load conversions.
22817 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22818   if (N->getValueType(0) != MVT::x86mmx ||
22819       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22820       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22821     return SDValue();
22822
22823   SDValue V = N->getOperand(0);
22824   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22825   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22826     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22827                        N->getValueType(0), V.getOperand(0));
22828
22829   return SDValue();
22830 }
22831
22832 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22833 /// generation and convert it from being a bunch of shuffles and extracts
22834 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22835 /// storing the value and loading scalars back, while for x64 we should
22836 /// use 64-bit extracts and shifts.
22837 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22838                                          TargetLowering::DAGCombinerInfo &DCI) {
22839   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22840     return NewOp;
22841
22842   SDValue InputVector = N->getOperand(0);
22843   SDLoc dl(InputVector);
22844   // Detect mmx to i32 conversion through a v2i32 elt extract.
22845   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22846       N->getValueType(0) == MVT::i32 &&
22847       InputVector.getValueType() == MVT::v2i32) {
22848
22849     // The bitcast source is a direct mmx result.
22850     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22851     if (MMXSrc.getValueType() == MVT::x86mmx)
22852       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22853                          N->getValueType(0),
22854                          InputVector.getNode()->getOperand(0));
22855
22856     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22857     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22858     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22859         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22860         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22861         MMXSrcOp.getValueType() == MVT::v1i64 &&
22862         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22863       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22864                          N->getValueType(0),
22865                          MMXSrcOp.getOperand(0));
22866   }
22867
22868   EVT VT = N->getValueType(0);
22869
22870   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22871       InputVector.getOpcode() == ISD::BITCAST &&
22872       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22873     uint64_t ExtractedElt =
22874         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22875     uint64_t InputValue =
22876         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22877     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22878     return DAG.getConstant(Res, dl, MVT::i1);
22879   }
22880   // Only operate on vectors of 4 elements, where the alternative shuffling
22881   // gets to be more expensive.
22882   if (InputVector.getValueType() != MVT::v4i32)
22883     return SDValue();
22884
22885   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22886   // single use which is a sign-extend or zero-extend, and all elements are
22887   // used.
22888   SmallVector<SDNode *, 4> Uses;
22889   unsigned ExtractedElements = 0;
22890   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22891        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22892     if (UI.getUse().getResNo() != InputVector.getResNo())
22893       return SDValue();
22894
22895     SDNode *Extract = *UI;
22896     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22897       return SDValue();
22898
22899     if (Extract->getValueType(0) != MVT::i32)
22900       return SDValue();
22901     if (!Extract->hasOneUse())
22902       return SDValue();
22903     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22904         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22905       return SDValue();
22906     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22907       return SDValue();
22908
22909     // Record which element was extracted.
22910     ExtractedElements |=
22911       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22912
22913     Uses.push_back(Extract);
22914   }
22915
22916   // If not all the elements were used, this may not be worthwhile.
22917   if (ExtractedElements != 15)
22918     return SDValue();
22919
22920   // Ok, we've now decided to do the transformation.
22921   // If 64-bit shifts are legal, use the extract-shift sequence,
22922   // otherwise bounce the vector off the cache.
22923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22924   SDValue Vals[4];
22925
22926   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22927     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22928     auto &DL = DAG.getDataLayout();
22929     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22930     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22931       DAG.getConstant(0, dl, VecIdxTy));
22932     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22933       DAG.getConstant(1, dl, VecIdxTy));
22934
22935     SDValue ShAmt = DAG.getConstant(
22936         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22937     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22938     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22939       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22940     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22941     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22942       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22943   } else {
22944     // Store the value to a temporary stack slot.
22945     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22946     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22947       MachinePointerInfo(), false, false, 0);
22948
22949     EVT ElementType = InputVector.getValueType().getVectorElementType();
22950     unsigned EltSize = ElementType.getSizeInBits() / 8;
22951
22952     // Replace each use (extract) with a load of the appropriate element.
22953     for (unsigned i = 0; i < 4; ++i) {
22954       uint64_t Offset = EltSize * i;
22955       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22956       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22957
22958       SDValue ScalarAddr =
22959           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22960
22961       // Load the scalar.
22962       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22963                             ScalarAddr, MachinePointerInfo(),
22964                             false, false, false, 0);
22965
22966     }
22967   }
22968
22969   // Replace the extracts
22970   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22971     UE = Uses.end(); UI != UE; ++UI) {
22972     SDNode *Extract = *UI;
22973
22974     SDValue Idx = Extract->getOperand(1);
22975     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22976     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22977   }
22978
22979   // The replacement was made in place; don't return anything.
22980   return SDValue();
22981 }
22982
22983 static SDValue
22984 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22985                                       const X86Subtarget *Subtarget) {
22986   SDLoc dl(N);
22987   SDValue Cond = N->getOperand(0);
22988   SDValue LHS = N->getOperand(1);
22989   SDValue RHS = N->getOperand(2);
22990
22991   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22992     SDValue CondSrc = Cond->getOperand(0);
22993     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22994       Cond = CondSrc->getOperand(0);
22995   }
22996
22997   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22998     return SDValue();
22999
23000   // A vselect where all conditions and data are constants can be optimized into
23001   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23002   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23003       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23004     return SDValue();
23005
23006   unsigned MaskValue = 0;
23007   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23008     return SDValue();
23009
23010   MVT VT = N->getSimpleValueType(0);
23011   unsigned NumElems = VT.getVectorNumElements();
23012   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23013   for (unsigned i = 0; i < NumElems; ++i) {
23014     // Be sure we emit undef where we can.
23015     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23016       ShuffleMask[i] = -1;
23017     else
23018       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23019   }
23020
23021   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23022   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23023     return SDValue();
23024   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23025 }
23026
23027 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23028 /// nodes.
23029 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23030                                     TargetLowering::DAGCombinerInfo &DCI,
23031                                     const X86Subtarget *Subtarget) {
23032   SDLoc DL(N);
23033   SDValue Cond = N->getOperand(0);
23034   // Get the LHS/RHS of the select.
23035   SDValue LHS = N->getOperand(1);
23036   SDValue RHS = N->getOperand(2);
23037   EVT VT = LHS.getValueType();
23038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23039
23040   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23041   // instructions match the semantics of the common C idiom x<y?x:y but not
23042   // x<=y?x:y, because of how they handle negative zero (which can be
23043   // ignored in unsafe-math mode).
23044   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23045   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23046       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23047       (Subtarget->hasSSE2() ||
23048        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23049     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23050
23051     unsigned Opcode = 0;
23052     // Check for x CC y ? x : y.
23053     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23054         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23055       switch (CC) {
23056       default: break;
23057       case ISD::SETULT:
23058         // Converting this to a min would handle NaNs incorrectly, and swapping
23059         // the operands would cause it to handle comparisons between positive
23060         // and negative zero incorrectly.
23061         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23062           if (!DAG.getTarget().Options.UnsafeFPMath &&
23063               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23064             break;
23065           std::swap(LHS, RHS);
23066         }
23067         Opcode = X86ISD::FMIN;
23068         break;
23069       case ISD::SETOLE:
23070         // Converting this to a min would handle comparisons between positive
23071         // and negative zero incorrectly.
23072         if (!DAG.getTarget().Options.UnsafeFPMath &&
23073             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23074           break;
23075         Opcode = X86ISD::FMIN;
23076         break;
23077       case ISD::SETULE:
23078         // Converting this to a min would handle both negative zeros and NaNs
23079         // incorrectly, but we can swap the operands to fix both.
23080         std::swap(LHS, RHS);
23081       case ISD::SETOLT:
23082       case ISD::SETLT:
23083       case ISD::SETLE:
23084         Opcode = X86ISD::FMIN;
23085         break;
23086
23087       case ISD::SETOGE:
23088         // Converting this to a max would handle comparisons between positive
23089         // and negative zero incorrectly.
23090         if (!DAG.getTarget().Options.UnsafeFPMath &&
23091             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23092           break;
23093         Opcode = X86ISD::FMAX;
23094         break;
23095       case ISD::SETUGT:
23096         // Converting this to a max would handle NaNs incorrectly, and swapping
23097         // the operands would cause it to handle comparisons between positive
23098         // and negative zero incorrectly.
23099         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23100           if (!DAG.getTarget().Options.UnsafeFPMath &&
23101               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23102             break;
23103           std::swap(LHS, RHS);
23104         }
23105         Opcode = X86ISD::FMAX;
23106         break;
23107       case ISD::SETUGE:
23108         // Converting this to a max would handle both negative zeros and NaNs
23109         // incorrectly, but we can swap the operands to fix both.
23110         std::swap(LHS, RHS);
23111       case ISD::SETOGT:
23112       case ISD::SETGT:
23113       case ISD::SETGE:
23114         Opcode = X86ISD::FMAX;
23115         break;
23116       }
23117     // Check for x CC y ? y : x -- a min/max with reversed arms.
23118     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23119                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23120       switch (CC) {
23121       default: break;
23122       case ISD::SETOGE:
23123         // Converting this to a min would handle comparisons between positive
23124         // and negative zero incorrectly, and swapping the operands would
23125         // cause it to handle NaNs incorrectly.
23126         if (!DAG.getTarget().Options.UnsafeFPMath &&
23127             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23128           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23129             break;
23130           std::swap(LHS, RHS);
23131         }
23132         Opcode = X86ISD::FMIN;
23133         break;
23134       case ISD::SETUGT:
23135         // Converting this to a min would handle NaNs incorrectly.
23136         if (!DAG.getTarget().Options.UnsafeFPMath &&
23137             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23138           break;
23139         Opcode = X86ISD::FMIN;
23140         break;
23141       case ISD::SETUGE:
23142         // Converting this to a min would handle both negative zeros and NaNs
23143         // incorrectly, but we can swap the operands to fix both.
23144         std::swap(LHS, RHS);
23145       case ISD::SETOGT:
23146       case ISD::SETGT:
23147       case ISD::SETGE:
23148         Opcode = X86ISD::FMIN;
23149         break;
23150
23151       case ISD::SETULT:
23152         // Converting this to a max would handle NaNs incorrectly.
23153         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23154           break;
23155         Opcode = X86ISD::FMAX;
23156         break;
23157       case ISD::SETOLE:
23158         // Converting this to a max would handle comparisons between positive
23159         // and negative zero incorrectly, and swapping the operands would
23160         // cause it to handle NaNs incorrectly.
23161         if (!DAG.getTarget().Options.UnsafeFPMath &&
23162             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23163           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23164             break;
23165           std::swap(LHS, RHS);
23166         }
23167         Opcode = X86ISD::FMAX;
23168         break;
23169       case ISD::SETULE:
23170         // Converting this to a max would handle both negative zeros and NaNs
23171         // incorrectly, but we can swap the operands to fix both.
23172         std::swap(LHS, RHS);
23173       case ISD::SETOLT:
23174       case ISD::SETLT:
23175       case ISD::SETLE:
23176         Opcode = X86ISD::FMAX;
23177         break;
23178       }
23179     }
23180
23181     if (Opcode)
23182       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23183   }
23184
23185   EVT CondVT = Cond.getValueType();
23186   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23187       CondVT.getVectorElementType() == MVT::i1) {
23188     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23189     // lowering on KNL. In this case we convert it to
23190     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23191     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23192     // Since SKX these selects have a proper lowering.
23193     EVT OpVT = LHS.getValueType();
23194     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23195         (OpVT.getVectorElementType() == MVT::i8 ||
23196          OpVT.getVectorElementType() == MVT::i16) &&
23197         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23198       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23199       DCI.AddToWorklist(Cond.getNode());
23200       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23201     }
23202   }
23203   // If this is a select between two integer constants, try to do some
23204   // optimizations.
23205   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23206     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23207       // Don't do this for crazy integer types.
23208       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23209         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23210         // so that TrueC (the true value) is larger than FalseC.
23211         bool NeedsCondInvert = false;
23212
23213         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23214             // Efficiently invertible.
23215             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23216              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23217               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23218           NeedsCondInvert = true;
23219           std::swap(TrueC, FalseC);
23220         }
23221
23222         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23223         if (FalseC->getAPIntValue() == 0 &&
23224             TrueC->getAPIntValue().isPowerOf2()) {
23225           if (NeedsCondInvert) // Invert the condition if needed.
23226             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23227                                DAG.getConstant(1, DL, Cond.getValueType()));
23228
23229           // Zero extend the condition if needed.
23230           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23231
23232           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23233           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23234                              DAG.getConstant(ShAmt, DL, MVT::i8));
23235         }
23236
23237         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23238         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23239           if (NeedsCondInvert) // Invert the condition if needed.
23240             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23241                                DAG.getConstant(1, DL, Cond.getValueType()));
23242
23243           // Zero extend the condition if needed.
23244           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23245                              FalseC->getValueType(0), Cond);
23246           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23247                              SDValue(FalseC, 0));
23248         }
23249
23250         // Optimize cases that will turn into an LEA instruction.  This requires
23251         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23252         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23253           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23254           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23255
23256           bool isFastMultiplier = false;
23257           if (Diff < 10) {
23258             switch ((unsigned char)Diff) {
23259               default: break;
23260               case 1:  // result = add base, cond
23261               case 2:  // result = lea base(    , cond*2)
23262               case 3:  // result = lea base(cond, cond*2)
23263               case 4:  // result = lea base(    , cond*4)
23264               case 5:  // result = lea base(cond, cond*4)
23265               case 8:  // result = lea base(    , cond*8)
23266               case 9:  // result = lea base(cond, cond*8)
23267                 isFastMultiplier = true;
23268                 break;
23269             }
23270           }
23271
23272           if (isFastMultiplier) {
23273             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23274             if (NeedsCondInvert) // Invert the condition if needed.
23275               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23276                                  DAG.getConstant(1, DL, Cond.getValueType()));
23277
23278             // Zero extend the condition if needed.
23279             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23280                                Cond);
23281             // Scale the condition by the difference.
23282             if (Diff != 1)
23283               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23284                                  DAG.getConstant(Diff, DL,
23285                                                  Cond.getValueType()));
23286
23287             // Add the base if non-zero.
23288             if (FalseC->getAPIntValue() != 0)
23289               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23290                                  SDValue(FalseC, 0));
23291             return Cond;
23292           }
23293         }
23294       }
23295   }
23296
23297   // Canonicalize max and min:
23298   // (x > y) ? x : y -> (x >= y) ? x : y
23299   // (x < y) ? x : y -> (x <= y) ? x : y
23300   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23301   // the need for an extra compare
23302   // against zero. e.g.
23303   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23304   // subl   %esi, %edi
23305   // testl  %edi, %edi
23306   // movl   $0, %eax
23307   // cmovgl %edi, %eax
23308   // =>
23309   // xorl   %eax, %eax
23310   // subl   %esi, $edi
23311   // cmovsl %eax, %edi
23312   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23313       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23314       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23315     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23316     switch (CC) {
23317     default: break;
23318     case ISD::SETLT:
23319     case ISD::SETGT: {
23320       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23321       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23322                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23323       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23324     }
23325     }
23326   }
23327
23328   // Early exit check
23329   if (!TLI.isTypeLegal(VT))
23330     return SDValue();
23331
23332   // Match VSELECTs into subs with unsigned saturation.
23333   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23334       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23335       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23336        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23337     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23338
23339     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23340     // left side invert the predicate to simplify logic below.
23341     SDValue Other;
23342     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23343       Other = RHS;
23344       CC = ISD::getSetCCInverse(CC, true);
23345     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23346       Other = LHS;
23347     }
23348
23349     if (Other.getNode() && Other->getNumOperands() == 2 &&
23350         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23351       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23352       SDValue CondRHS = Cond->getOperand(1);
23353
23354       // Look for a general sub with unsigned saturation first.
23355       // x >= y ? x-y : 0 --> subus x, y
23356       // x >  y ? x-y : 0 --> subus x, y
23357       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23358           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23359         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23360
23361       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23362         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23363           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23364             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23365               // If the RHS is a constant we have to reverse the const
23366               // canonicalization.
23367               // x > C-1 ? x+-C : 0 --> subus x, C
23368               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23369                   CondRHSConst->getAPIntValue() ==
23370                       (-OpRHSConst->getAPIntValue() - 1))
23371                 return DAG.getNode(
23372                     X86ISD::SUBUS, DL, VT, OpLHS,
23373                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23374
23375           // Another special case: If C was a sign bit, the sub has been
23376           // canonicalized into a xor.
23377           // FIXME: Would it be better to use computeKnownBits to determine
23378           //        whether it's safe to decanonicalize the xor?
23379           // x s< 0 ? x^C : 0 --> subus x, C
23380           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23381               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23382               OpRHSConst->getAPIntValue().isSignBit())
23383             // Note that we have to rebuild the RHS constant here to ensure we
23384             // don't rely on particular values of undef lanes.
23385             return DAG.getNode(
23386                 X86ISD::SUBUS, DL, VT, OpLHS,
23387                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23388         }
23389     }
23390   }
23391
23392   // Simplify vector selection if condition value type matches vselect
23393   // operand type
23394   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23395     assert(Cond.getValueType().isVector() &&
23396            "vector select expects a vector selector!");
23397
23398     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23399     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23400
23401     // Try invert the condition if true value is not all 1s and false value
23402     // is not all 0s.
23403     if (!TValIsAllOnes && !FValIsAllZeros &&
23404         // Check if the selector will be produced by CMPP*/PCMP*
23405         Cond.getOpcode() == ISD::SETCC &&
23406         // Check if SETCC has already been promoted
23407         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23408             CondVT) {
23409       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23410       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23411
23412       if (TValIsAllZeros || FValIsAllOnes) {
23413         SDValue CC = Cond.getOperand(2);
23414         ISD::CondCode NewCC =
23415           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23416                                Cond.getOperand(0).getValueType().isInteger());
23417         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23418         std::swap(LHS, RHS);
23419         TValIsAllOnes = FValIsAllOnes;
23420         FValIsAllZeros = TValIsAllZeros;
23421       }
23422     }
23423
23424     if (TValIsAllOnes || FValIsAllZeros) {
23425       SDValue Ret;
23426
23427       if (TValIsAllOnes && FValIsAllZeros)
23428         Ret = Cond;
23429       else if (TValIsAllOnes)
23430         Ret =
23431             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23432       else if (FValIsAllZeros)
23433         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23434                           DAG.getBitcast(CondVT, LHS));
23435
23436       return DAG.getBitcast(VT, Ret);
23437     }
23438   }
23439
23440   // We should generate an X86ISD::BLENDI from a vselect if its argument
23441   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23442   // constants. This specific pattern gets generated when we split a
23443   // selector for a 512 bit vector in a machine without AVX512 (but with
23444   // 256-bit vectors), during legalization:
23445   //
23446   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23447   //
23448   // Iff we find this pattern and the build_vectors are built from
23449   // constants, we translate the vselect into a shuffle_vector that we
23450   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23451   if ((N->getOpcode() == ISD::VSELECT ||
23452        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23453       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23454     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23455     if (Shuffle.getNode())
23456       return Shuffle;
23457   }
23458
23459   // If this is a *dynamic* select (non-constant condition) and we can match
23460   // this node with one of the variable blend instructions, restructure the
23461   // condition so that the blends can use the high bit of each element and use
23462   // SimplifyDemandedBits to simplify the condition operand.
23463   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23464       !DCI.isBeforeLegalize() &&
23465       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23466     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23467
23468     // Don't optimize vector selects that map to mask-registers.
23469     if (BitWidth == 1)
23470       return SDValue();
23471
23472     // We can only handle the cases where VSELECT is directly legal on the
23473     // subtarget. We custom lower VSELECT nodes with constant conditions and
23474     // this makes it hard to see whether a dynamic VSELECT will correctly
23475     // lower, so we both check the operation's status and explicitly handle the
23476     // cases where a *dynamic* blend will fail even though a constant-condition
23477     // blend could be custom lowered.
23478     // FIXME: We should find a better way to handle this class of problems.
23479     // Potentially, we should combine constant-condition vselect nodes
23480     // pre-legalization into shuffles and not mark as many types as custom
23481     // lowered.
23482     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23483       return SDValue();
23484     // FIXME: We don't support i16-element blends currently. We could and
23485     // should support them by making *all* the bits in the condition be set
23486     // rather than just the high bit and using an i8-element blend.
23487     if (VT.getScalarType() == MVT::i16)
23488       return SDValue();
23489     // Dynamic blending was only available from SSE4.1 onward.
23490     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23491       return SDValue();
23492     // Byte blends are only available in AVX2
23493     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23494         !Subtarget->hasAVX2())
23495       return SDValue();
23496
23497     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23498     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23499
23500     APInt KnownZero, KnownOne;
23501     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23502                                           DCI.isBeforeLegalizeOps());
23503     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23504         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23505                                  TLO)) {
23506       // If we changed the computation somewhere in the DAG, this change
23507       // will affect all users of Cond.
23508       // Make sure it is fine and update all the nodes so that we do not
23509       // use the generic VSELECT anymore. Otherwise, we may perform
23510       // wrong optimizations as we messed up with the actual expectation
23511       // for the vector boolean values.
23512       if (Cond != TLO.Old) {
23513         // Check all uses of that condition operand to check whether it will be
23514         // consumed by non-BLEND instructions, which may depend on all bits are
23515         // set properly.
23516         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23517              I != E; ++I)
23518           if (I->getOpcode() != ISD::VSELECT)
23519             // TODO: Add other opcodes eventually lowered into BLEND.
23520             return SDValue();
23521
23522         // Update all the users of the condition, before committing the change,
23523         // so that the VSELECT optimizations that expect the correct vector
23524         // boolean value will not be triggered.
23525         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23526              I != E; ++I)
23527           DAG.ReplaceAllUsesOfValueWith(
23528               SDValue(*I, 0),
23529               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23530                           Cond, I->getOperand(1), I->getOperand(2)));
23531         DCI.CommitTargetLoweringOpt(TLO);
23532         return SDValue();
23533       }
23534       // At this point, only Cond is changed. Change the condition
23535       // just for N to keep the opportunity to optimize all other
23536       // users their own way.
23537       DAG.ReplaceAllUsesOfValueWith(
23538           SDValue(N, 0),
23539           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23540                       TLO.New, N->getOperand(1), N->getOperand(2)));
23541       return SDValue();
23542     }
23543   }
23544
23545   return SDValue();
23546 }
23547
23548 // Check whether a boolean test is testing a boolean value generated by
23549 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23550 // code.
23551 //
23552 // Simplify the following patterns:
23553 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23554 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23555 // to (Op EFLAGS Cond)
23556 //
23557 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23558 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23559 // to (Op EFLAGS !Cond)
23560 //
23561 // where Op could be BRCOND or CMOV.
23562 //
23563 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23564   // Quit if not CMP and SUB with its value result used.
23565   if (Cmp.getOpcode() != X86ISD::CMP &&
23566       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23567       return SDValue();
23568
23569   // Quit if not used as a boolean value.
23570   if (CC != X86::COND_E && CC != X86::COND_NE)
23571     return SDValue();
23572
23573   // Check CMP operands. One of them should be 0 or 1 and the other should be
23574   // an SetCC or extended from it.
23575   SDValue Op1 = Cmp.getOperand(0);
23576   SDValue Op2 = Cmp.getOperand(1);
23577
23578   SDValue SetCC;
23579   const ConstantSDNode* C = nullptr;
23580   bool needOppositeCond = (CC == X86::COND_E);
23581   bool checkAgainstTrue = false; // Is it a comparison against 1?
23582
23583   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23584     SetCC = Op2;
23585   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23586     SetCC = Op1;
23587   else // Quit if all operands are not constants.
23588     return SDValue();
23589
23590   if (C->getZExtValue() == 1) {
23591     needOppositeCond = !needOppositeCond;
23592     checkAgainstTrue = true;
23593   } else if (C->getZExtValue() != 0)
23594     // Quit if the constant is neither 0 or 1.
23595     return SDValue();
23596
23597   bool truncatedToBoolWithAnd = false;
23598   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23599   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23600          SetCC.getOpcode() == ISD::TRUNCATE ||
23601          SetCC.getOpcode() == ISD::AND) {
23602     if (SetCC.getOpcode() == ISD::AND) {
23603       int OpIdx = -1;
23604       ConstantSDNode *CS;
23605       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23606           CS->getZExtValue() == 1)
23607         OpIdx = 1;
23608       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23609           CS->getZExtValue() == 1)
23610         OpIdx = 0;
23611       if (OpIdx == -1)
23612         break;
23613       SetCC = SetCC.getOperand(OpIdx);
23614       truncatedToBoolWithAnd = true;
23615     } else
23616       SetCC = SetCC.getOperand(0);
23617   }
23618
23619   switch (SetCC.getOpcode()) {
23620   case X86ISD::SETCC_CARRY:
23621     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23622     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23623     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23624     // truncated to i1 using 'and'.
23625     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23626       break;
23627     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23628            "Invalid use of SETCC_CARRY!");
23629     // FALL THROUGH
23630   case X86ISD::SETCC:
23631     // Set the condition code or opposite one if necessary.
23632     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23633     if (needOppositeCond)
23634       CC = X86::GetOppositeBranchCondition(CC);
23635     return SetCC.getOperand(1);
23636   case X86ISD::CMOV: {
23637     // Check whether false/true value has canonical one, i.e. 0 or 1.
23638     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23639     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23640     // Quit if true value is not a constant.
23641     if (!TVal)
23642       return SDValue();
23643     // Quit if false value is not a constant.
23644     if (!FVal) {
23645       SDValue Op = SetCC.getOperand(0);
23646       // Skip 'zext' or 'trunc' node.
23647       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23648           Op.getOpcode() == ISD::TRUNCATE)
23649         Op = Op.getOperand(0);
23650       // A special case for rdrand/rdseed, where 0 is set if false cond is
23651       // found.
23652       if ((Op.getOpcode() != X86ISD::RDRAND &&
23653            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23654         return SDValue();
23655     }
23656     // Quit if false value is not the constant 0 or 1.
23657     bool FValIsFalse = true;
23658     if (FVal && FVal->getZExtValue() != 0) {
23659       if (FVal->getZExtValue() != 1)
23660         return SDValue();
23661       // If FVal is 1, opposite cond is needed.
23662       needOppositeCond = !needOppositeCond;
23663       FValIsFalse = false;
23664     }
23665     // Quit if TVal is not the constant opposite of FVal.
23666     if (FValIsFalse && TVal->getZExtValue() != 1)
23667       return SDValue();
23668     if (!FValIsFalse && TVal->getZExtValue() != 0)
23669       return SDValue();
23670     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23671     if (needOppositeCond)
23672       CC = X86::GetOppositeBranchCondition(CC);
23673     return SetCC.getOperand(3);
23674   }
23675   }
23676
23677   return SDValue();
23678 }
23679
23680 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23681 /// Match:
23682 ///   (X86or (X86setcc) (X86setcc))
23683 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23684 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23685                                            X86::CondCode &CC1, SDValue &Flags,
23686                                            bool &isAnd) {
23687   if (Cond->getOpcode() == X86ISD::CMP) {
23688     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23689     if (!CondOp1C || !CondOp1C->isNullValue())
23690       return false;
23691
23692     Cond = Cond->getOperand(0);
23693   }
23694
23695   isAnd = false;
23696
23697   SDValue SetCC0, SetCC1;
23698   switch (Cond->getOpcode()) {
23699   default: return false;
23700   case ISD::AND:
23701   case X86ISD::AND:
23702     isAnd = true;
23703     // fallthru
23704   case ISD::OR:
23705   case X86ISD::OR:
23706     SetCC0 = Cond->getOperand(0);
23707     SetCC1 = Cond->getOperand(1);
23708     break;
23709   };
23710
23711   // Make sure we have SETCC nodes, using the same flags value.
23712   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23713       SetCC1.getOpcode() != X86ISD::SETCC ||
23714       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23715     return false;
23716
23717   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23718   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23719   Flags = SetCC0->getOperand(1);
23720   return true;
23721 }
23722
23723 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23724 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23725                                   TargetLowering::DAGCombinerInfo &DCI,
23726                                   const X86Subtarget *Subtarget) {
23727   SDLoc DL(N);
23728
23729   // If the flag operand isn't dead, don't touch this CMOV.
23730   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23731     return SDValue();
23732
23733   SDValue FalseOp = N->getOperand(0);
23734   SDValue TrueOp = N->getOperand(1);
23735   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23736   SDValue Cond = N->getOperand(3);
23737
23738   if (CC == X86::COND_E || CC == X86::COND_NE) {
23739     switch (Cond.getOpcode()) {
23740     default: break;
23741     case X86ISD::BSR:
23742     case X86ISD::BSF:
23743       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23744       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23745         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23746     }
23747   }
23748
23749   SDValue Flags;
23750
23751   Flags = checkBoolTestSetCCCombine(Cond, CC);
23752   if (Flags.getNode() &&
23753       // Extra check as FCMOV only supports a subset of X86 cond.
23754       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23755     SDValue Ops[] = { FalseOp, TrueOp,
23756                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23757     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23758   }
23759
23760   // If this is a select between two integer constants, try to do some
23761   // optimizations.  Note that the operands are ordered the opposite of SELECT
23762   // operands.
23763   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23764     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23765       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23766       // larger than FalseC (the false value).
23767       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23768         CC = X86::GetOppositeBranchCondition(CC);
23769         std::swap(TrueC, FalseC);
23770         std::swap(TrueOp, FalseOp);
23771       }
23772
23773       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23774       // This is efficient for any integer data type (including i8/i16) and
23775       // shift amount.
23776       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23777         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23778                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23779
23780         // Zero extend the condition if needed.
23781         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23782
23783         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23784         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23785                            DAG.getConstant(ShAmt, DL, MVT::i8));
23786         if (N->getNumValues() == 2)  // Dead flag value?
23787           return DCI.CombineTo(N, Cond, SDValue());
23788         return Cond;
23789       }
23790
23791       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23792       // for any integer data type, including i8/i16.
23793       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23794         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23795                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23796
23797         // Zero extend the condition if needed.
23798         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23799                            FalseC->getValueType(0), Cond);
23800         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23801                            SDValue(FalseC, 0));
23802
23803         if (N->getNumValues() == 2)  // Dead flag value?
23804           return DCI.CombineTo(N, Cond, SDValue());
23805         return Cond;
23806       }
23807
23808       // Optimize cases that will turn into an LEA instruction.  This requires
23809       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23810       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23811         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23812         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23813
23814         bool isFastMultiplier = false;
23815         if (Diff < 10) {
23816           switch ((unsigned char)Diff) {
23817           default: break;
23818           case 1:  // result = add base, cond
23819           case 2:  // result = lea base(    , cond*2)
23820           case 3:  // result = lea base(cond, cond*2)
23821           case 4:  // result = lea base(    , cond*4)
23822           case 5:  // result = lea base(cond, cond*4)
23823           case 8:  // result = lea base(    , cond*8)
23824           case 9:  // result = lea base(cond, cond*8)
23825             isFastMultiplier = true;
23826             break;
23827           }
23828         }
23829
23830         if (isFastMultiplier) {
23831           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23832           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23833                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23834           // Zero extend the condition if needed.
23835           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23836                              Cond);
23837           // Scale the condition by the difference.
23838           if (Diff != 1)
23839             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23840                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23841
23842           // Add the base if non-zero.
23843           if (FalseC->getAPIntValue() != 0)
23844             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23845                                SDValue(FalseC, 0));
23846           if (N->getNumValues() == 2)  // Dead flag value?
23847             return DCI.CombineTo(N, Cond, SDValue());
23848           return Cond;
23849         }
23850       }
23851     }
23852   }
23853
23854   // Handle these cases:
23855   //   (select (x != c), e, c) -> select (x != c), e, x),
23856   //   (select (x == c), c, e) -> select (x == c), x, e)
23857   // where the c is an integer constant, and the "select" is the combination
23858   // of CMOV and CMP.
23859   //
23860   // The rationale for this change is that the conditional-move from a constant
23861   // needs two instructions, however, conditional-move from a register needs
23862   // only one instruction.
23863   //
23864   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23865   //  some instruction-combining opportunities. This opt needs to be
23866   //  postponed as late as possible.
23867   //
23868   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23869     // the DCI.xxxx conditions are provided to postpone the optimization as
23870     // late as possible.
23871
23872     ConstantSDNode *CmpAgainst = nullptr;
23873     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23874         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23875         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23876
23877       if (CC == X86::COND_NE &&
23878           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23879         CC = X86::GetOppositeBranchCondition(CC);
23880         std::swap(TrueOp, FalseOp);
23881       }
23882
23883       if (CC == X86::COND_E &&
23884           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23885         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23886                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23887         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23888       }
23889     }
23890   }
23891
23892   // Fold and/or of setcc's to double CMOV:
23893   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23894   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23895   //
23896   // This combine lets us generate:
23897   //   cmovcc1 (jcc1 if we don't have CMOV)
23898   //   cmovcc2 (same)
23899   // instead of:
23900   //   setcc1
23901   //   setcc2
23902   //   and/or
23903   //   cmovne (jne if we don't have CMOV)
23904   // When we can't use the CMOV instruction, it might increase branch
23905   // mispredicts.
23906   // When we can use CMOV, or when there is no mispredict, this improves
23907   // throughput and reduces register pressure.
23908   //
23909   if (CC == X86::COND_NE) {
23910     SDValue Flags;
23911     X86::CondCode CC0, CC1;
23912     bool isAndSetCC;
23913     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23914       if (isAndSetCC) {
23915         std::swap(FalseOp, TrueOp);
23916         CC0 = X86::GetOppositeBranchCondition(CC0);
23917         CC1 = X86::GetOppositeBranchCondition(CC1);
23918       }
23919
23920       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23921         Flags};
23922       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23923       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23924       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23925       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23926       return CMOV;
23927     }
23928   }
23929
23930   return SDValue();
23931 }
23932
23933 /// PerformMulCombine - Optimize a single multiply with constant into two
23934 /// in order to implement it with two cheaper instructions, e.g.
23935 /// LEA + SHL, LEA + LEA.
23936 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23937                                  TargetLowering::DAGCombinerInfo &DCI) {
23938   // An imul is usually smaller than the alternative sequence.
23939   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23940     return SDValue();
23941
23942   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23943     return SDValue();
23944
23945   EVT VT = N->getValueType(0);
23946   if (VT != MVT::i64 && VT != MVT::i32)
23947     return SDValue();
23948
23949   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23950   if (!C)
23951     return SDValue();
23952   uint64_t MulAmt = C->getZExtValue();
23953   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23954     return SDValue();
23955
23956   uint64_t MulAmt1 = 0;
23957   uint64_t MulAmt2 = 0;
23958   if ((MulAmt % 9) == 0) {
23959     MulAmt1 = 9;
23960     MulAmt2 = MulAmt / 9;
23961   } else if ((MulAmt % 5) == 0) {
23962     MulAmt1 = 5;
23963     MulAmt2 = MulAmt / 5;
23964   } else if ((MulAmt % 3) == 0) {
23965     MulAmt1 = 3;
23966     MulAmt2 = MulAmt / 3;
23967   }
23968   if (MulAmt2 &&
23969       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23970     SDLoc DL(N);
23971
23972     if (isPowerOf2_64(MulAmt2) &&
23973         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23974       // If second multiplifer is pow2, issue it first. We want the multiply by
23975       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23976       // is an add.
23977       std::swap(MulAmt1, MulAmt2);
23978
23979     SDValue NewMul;
23980     if (isPowerOf2_64(MulAmt1))
23981       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23982                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23983     else
23984       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23985                            DAG.getConstant(MulAmt1, DL, VT));
23986
23987     if (isPowerOf2_64(MulAmt2))
23988       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23989                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23990     else
23991       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23992                            DAG.getConstant(MulAmt2, DL, VT));
23993
23994     // Do not add new nodes to DAG combiner worklist.
23995     DCI.CombineTo(N, NewMul, false);
23996   }
23997   return SDValue();
23998 }
23999
24000 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24001   SDValue N0 = N->getOperand(0);
24002   SDValue N1 = N->getOperand(1);
24003   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24004   EVT VT = N0.getValueType();
24005
24006   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24007   // since the result of setcc_c is all zero's or all ones.
24008   if (VT.isInteger() && !VT.isVector() &&
24009       N1C && N0.getOpcode() == ISD::AND &&
24010       N0.getOperand(1).getOpcode() == ISD::Constant) {
24011     SDValue N00 = N0.getOperand(0);
24012     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24013     APInt ShAmt = N1C->getAPIntValue();
24014     Mask = Mask.shl(ShAmt);
24015     bool MaskOK = false;
24016     // We can handle cases concerning bit-widening nodes containing setcc_c if
24017     // we carefully interrogate the mask to make sure we are semantics
24018     // preserving.
24019     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24020     // of the underlying setcc_c operation if the setcc_c was zero extended.
24021     // Consider the following example:
24022     //   zext(setcc_c)                 -> i32 0x0000FFFF
24023     //   c1                            -> i32 0x0000FFFF
24024     //   c2                            -> i32 0x00000001
24025     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24026     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24027     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24028       MaskOK = true;
24029     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24030                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24031       MaskOK = true;
24032     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24033                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24034                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24035       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24036     }
24037     if (MaskOK && Mask != 0) {
24038       SDLoc DL(N);
24039       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24040     }
24041   }
24042
24043   // Hardware support for vector shifts is sparse which makes us scalarize the
24044   // vector operations in many cases. Also, on sandybridge ADD is faster than
24045   // shl.
24046   // (shl V, 1) -> add V,V
24047   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24048     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24049       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24050       // We shift all of the values by one. In many cases we do not have
24051       // hardware support for this operation. This is better expressed as an ADD
24052       // of two values.
24053       if (N1SplatC->getAPIntValue() == 1)
24054         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24055     }
24056
24057   return SDValue();
24058 }
24059
24060 /// \brief Returns a vector of 0s if the node in input is a vector logical
24061 /// shift by a constant amount which is known to be bigger than or equal
24062 /// to the vector element size in bits.
24063 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24064                                       const X86Subtarget *Subtarget) {
24065   EVT VT = N->getValueType(0);
24066
24067   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24068       (!Subtarget->hasInt256() ||
24069        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24070     return SDValue();
24071
24072   SDValue Amt = N->getOperand(1);
24073   SDLoc DL(N);
24074   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24075     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24076       APInt ShiftAmt = AmtSplat->getAPIntValue();
24077       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24078
24079       // SSE2/AVX2 logical shifts always return a vector of 0s
24080       // if the shift amount is bigger than or equal to
24081       // the element size. The constant shift amount will be
24082       // encoded as a 8-bit immediate.
24083       if (ShiftAmt.trunc(8).uge(MaxAmount))
24084         return getZeroVector(VT, Subtarget, DAG, DL);
24085     }
24086
24087   return SDValue();
24088 }
24089
24090 /// PerformShiftCombine - Combine shifts.
24091 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24092                                    TargetLowering::DAGCombinerInfo &DCI,
24093                                    const X86Subtarget *Subtarget) {
24094   if (N->getOpcode() == ISD::SHL)
24095     if (SDValue V = PerformSHLCombine(N, DAG))
24096       return V;
24097
24098   // Try to fold this logical shift into a zero vector.
24099   if (N->getOpcode() != ISD::SRA)
24100     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24101       return V;
24102
24103   return SDValue();
24104 }
24105
24106 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24107 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24108 // and friends.  Likewise for OR -> CMPNEQSS.
24109 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24110                             TargetLowering::DAGCombinerInfo &DCI,
24111                             const X86Subtarget *Subtarget) {
24112   unsigned opcode;
24113
24114   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24115   // we're requiring SSE2 for both.
24116   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24117     SDValue N0 = N->getOperand(0);
24118     SDValue N1 = N->getOperand(1);
24119     SDValue CMP0 = N0->getOperand(1);
24120     SDValue CMP1 = N1->getOperand(1);
24121     SDLoc DL(N);
24122
24123     // The SETCCs should both refer to the same CMP.
24124     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24125       return SDValue();
24126
24127     SDValue CMP00 = CMP0->getOperand(0);
24128     SDValue CMP01 = CMP0->getOperand(1);
24129     EVT     VT    = CMP00.getValueType();
24130
24131     if (VT == MVT::f32 || VT == MVT::f64) {
24132       bool ExpectingFlags = false;
24133       // Check for any users that want flags:
24134       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24135            !ExpectingFlags && UI != UE; ++UI)
24136         switch (UI->getOpcode()) {
24137         default:
24138         case ISD::BR_CC:
24139         case ISD::BRCOND:
24140         case ISD::SELECT:
24141           ExpectingFlags = true;
24142           break;
24143         case ISD::CopyToReg:
24144         case ISD::SIGN_EXTEND:
24145         case ISD::ZERO_EXTEND:
24146         case ISD::ANY_EXTEND:
24147           break;
24148         }
24149
24150       if (!ExpectingFlags) {
24151         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24152         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24153
24154         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24155           X86::CondCode tmp = cc0;
24156           cc0 = cc1;
24157           cc1 = tmp;
24158         }
24159
24160         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24161             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24162           // FIXME: need symbolic constants for these magic numbers.
24163           // See X86ATTInstPrinter.cpp:printSSECC().
24164           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24165           if (Subtarget->hasAVX512()) {
24166             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24167                                          CMP01,
24168                                          DAG.getConstant(x86cc, DL, MVT::i8));
24169             if (N->getValueType(0) != MVT::i1)
24170               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24171                                  FSetCC);
24172             return FSetCC;
24173           }
24174           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24175                                               CMP00.getValueType(), CMP00, CMP01,
24176                                               DAG.getConstant(x86cc, DL,
24177                                                               MVT::i8));
24178
24179           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24180           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24181
24182           if (is64BitFP && !Subtarget->is64Bit()) {
24183             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24184             // 64-bit integer, since that's not a legal type. Since
24185             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24186             // bits, but can do this little dance to extract the lowest 32 bits
24187             // and work with those going forward.
24188             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24189                                            OnesOrZeroesF);
24190             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24191             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24192                                         Vector32, DAG.getIntPtrConstant(0, DL));
24193             IntVT = MVT::i32;
24194           }
24195
24196           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24197           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24198                                       DAG.getConstant(1, DL, IntVT));
24199           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24200                                               ANDed);
24201           return OneBitOfTruth;
24202         }
24203       }
24204     }
24205   }
24206   return SDValue();
24207 }
24208
24209 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24210 /// so it can be folded inside ANDNP.
24211 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24212   EVT VT = N->getValueType(0);
24213
24214   // Match direct AllOnes for 128 and 256-bit vectors
24215   if (ISD::isBuildVectorAllOnes(N))
24216     return true;
24217
24218   // Look through a bit convert.
24219   if (N->getOpcode() == ISD::BITCAST)
24220     N = N->getOperand(0).getNode();
24221
24222   // Sometimes the operand may come from a insert_subvector building a 256-bit
24223   // allones vector
24224   if (VT.is256BitVector() &&
24225       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24226     SDValue V1 = N->getOperand(0);
24227     SDValue V2 = N->getOperand(1);
24228
24229     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24230         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24231         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24232         ISD::isBuildVectorAllOnes(V2.getNode()))
24233       return true;
24234   }
24235
24236   return false;
24237 }
24238
24239 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24240 // register. In most cases we actually compare or select YMM-sized registers
24241 // and mixing the two types creates horrible code. This method optimizes
24242 // some of the transition sequences.
24243 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24244                                  TargetLowering::DAGCombinerInfo &DCI,
24245                                  const X86Subtarget *Subtarget) {
24246   EVT VT = N->getValueType(0);
24247   if (!VT.is256BitVector())
24248     return SDValue();
24249
24250   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24251           N->getOpcode() == ISD::ZERO_EXTEND ||
24252           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24253
24254   SDValue Narrow = N->getOperand(0);
24255   EVT NarrowVT = Narrow->getValueType(0);
24256   if (!NarrowVT.is128BitVector())
24257     return SDValue();
24258
24259   if (Narrow->getOpcode() != ISD::XOR &&
24260       Narrow->getOpcode() != ISD::AND &&
24261       Narrow->getOpcode() != ISD::OR)
24262     return SDValue();
24263
24264   SDValue N0  = Narrow->getOperand(0);
24265   SDValue N1  = Narrow->getOperand(1);
24266   SDLoc DL(Narrow);
24267
24268   // The Left side has to be a trunc.
24269   if (N0.getOpcode() != ISD::TRUNCATE)
24270     return SDValue();
24271
24272   // The type of the truncated inputs.
24273   EVT WideVT = N0->getOperand(0)->getValueType(0);
24274   if (WideVT != VT)
24275     return SDValue();
24276
24277   // The right side has to be a 'trunc' or a constant vector.
24278   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24279   ConstantSDNode *RHSConstSplat = nullptr;
24280   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24281     RHSConstSplat = RHSBV->getConstantSplatNode();
24282   if (!RHSTrunc && !RHSConstSplat)
24283     return SDValue();
24284
24285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24286
24287   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24288     return SDValue();
24289
24290   // Set N0 and N1 to hold the inputs to the new wide operation.
24291   N0 = N0->getOperand(0);
24292   if (RHSConstSplat) {
24293     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24294                      SDValue(RHSConstSplat, 0));
24295     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24296     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24297   } else if (RHSTrunc) {
24298     N1 = N1->getOperand(0);
24299   }
24300
24301   // Generate the wide operation.
24302   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24303   unsigned Opcode = N->getOpcode();
24304   switch (Opcode) {
24305   case ISD::ANY_EXTEND:
24306     return Op;
24307   case ISD::ZERO_EXTEND: {
24308     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24309     APInt Mask = APInt::getAllOnesValue(InBits);
24310     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24311     return DAG.getNode(ISD::AND, DL, VT,
24312                        Op, DAG.getConstant(Mask, DL, VT));
24313   }
24314   case ISD::SIGN_EXTEND:
24315     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24316                        Op, DAG.getValueType(NarrowVT));
24317   default:
24318     llvm_unreachable("Unexpected opcode");
24319   }
24320 }
24321
24322 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24323                                  TargetLowering::DAGCombinerInfo &DCI,
24324                                  const X86Subtarget *Subtarget) {
24325   SDValue N0 = N->getOperand(0);
24326   SDValue N1 = N->getOperand(1);
24327   SDLoc DL(N);
24328
24329   // A vector zext_in_reg may be represented as a shuffle,
24330   // feeding into a bitcast (this represents anyext) feeding into
24331   // an and with a mask.
24332   // We'd like to try to combine that into a shuffle with zero
24333   // plus a bitcast, removing the and.
24334   if (N0.getOpcode() != ISD::BITCAST ||
24335       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24336     return SDValue();
24337
24338   // The other side of the AND should be a splat of 2^C, where C
24339   // is the number of bits in the source type.
24340   if (N1.getOpcode() == ISD::BITCAST)
24341     N1 = N1.getOperand(0);
24342   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24343     return SDValue();
24344   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24345
24346   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24347   EVT SrcType = Shuffle->getValueType(0);
24348
24349   // We expect a single-source shuffle
24350   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24351     return SDValue();
24352
24353   unsigned SrcSize = SrcType.getScalarSizeInBits();
24354
24355   APInt SplatValue, SplatUndef;
24356   unsigned SplatBitSize;
24357   bool HasAnyUndefs;
24358   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24359                                 SplatBitSize, HasAnyUndefs))
24360     return SDValue();
24361
24362   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24363   // Make sure the splat matches the mask we expect
24364   if (SplatBitSize > ResSize ||
24365       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24366     return SDValue();
24367
24368   // Make sure the input and output size make sense
24369   if (SrcSize >= ResSize || ResSize % SrcSize)
24370     return SDValue();
24371
24372   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24373   // The number of u's between each two values depends on the ratio between
24374   // the source and dest type.
24375   unsigned ZextRatio = ResSize / SrcSize;
24376   bool IsZext = true;
24377   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24378     if (i % ZextRatio) {
24379       if (Shuffle->getMaskElt(i) > 0) {
24380         // Expected undef
24381         IsZext = false;
24382         break;
24383       }
24384     } else {
24385       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24386         // Expected element number
24387         IsZext = false;
24388         break;
24389       }
24390     }
24391   }
24392
24393   if (!IsZext)
24394     return SDValue();
24395
24396   // Ok, perform the transformation - replace the shuffle with
24397   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24398   // (instead of undef) where the k elements come from the zero vector.
24399   SmallVector<int, 8> Mask;
24400   unsigned NumElems = SrcType.getVectorNumElements();
24401   for (unsigned i = 0; i < NumElems; ++i)
24402     if (i % ZextRatio)
24403       Mask.push_back(NumElems);
24404     else
24405       Mask.push_back(i / ZextRatio);
24406
24407   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24408     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24409   return DAG.getBitcast(N0.getValueType(), NewShuffle);
24410 }
24411
24412 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24413                                  TargetLowering::DAGCombinerInfo &DCI,
24414                                  const X86Subtarget *Subtarget) {
24415   if (DCI.isBeforeLegalizeOps())
24416     return SDValue();
24417
24418   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24419     return Zext;
24420
24421   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24422     return R;
24423
24424   EVT VT = N->getValueType(0);
24425   SDValue N0 = N->getOperand(0);
24426   SDValue N1 = N->getOperand(1);
24427   SDLoc DL(N);
24428
24429   // Create BEXTR instructions
24430   // BEXTR is ((X >> imm) & (2**size-1))
24431   if (VT == MVT::i32 || VT == MVT::i64) {
24432     // Check for BEXTR.
24433     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24434         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24435       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24436       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24437       if (MaskNode && ShiftNode) {
24438         uint64_t Mask = MaskNode->getZExtValue();
24439         uint64_t Shift = ShiftNode->getZExtValue();
24440         if (isMask_64(Mask)) {
24441           uint64_t MaskSize = countPopulation(Mask);
24442           if (Shift + MaskSize <= VT.getSizeInBits())
24443             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24444                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24445                                                VT));
24446         }
24447       }
24448     } // BEXTR
24449
24450     // If both input operands are being cast from floating point types,
24451     // try to convert this into a floating point logic node to avoid
24452     // unnecessary moves from SSE to integer registers.
24453     // FIXME: Split this into a helper function, so it can also be used with
24454     //        or/xor combining.
24455     if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
24456         ((Subtarget->hasSSE1() && VT == MVT::i32) ||
24457          (Subtarget->hasSSE2() && VT == MVT::i64))) {
24458       SDValue N00 = N0.getOperand(0);
24459       SDValue N10 = N1.getOperand(0);
24460       EVT N00Type = N00.getValueType();
24461       EVT N10Type = N10.getValueType();
24462       if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
24463         SDValue FLogic = DAG.getNode(X86ISD::FAND, DL, N00Type, N00, N10);
24464         return DAG.getBitcast(VT, FLogic);
24465       }
24466     }
24467
24468     return SDValue();
24469   }
24470
24471   // Want to form ANDNP nodes:
24472   // 1) In the hopes of then easily combining them with OR and AND nodes
24473   //    to form PBLEND/PSIGN.
24474   // 2) To match ANDN packed intrinsics
24475   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24476     return SDValue();
24477
24478   // Check LHS for vnot
24479   if (N0.getOpcode() == ISD::XOR &&
24480       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24481       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24482     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24483
24484   // Check RHS for vnot
24485   if (N1.getOpcode() == ISD::XOR &&
24486       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24487       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24488     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24489
24490   return SDValue();
24491 }
24492
24493 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24494                                 TargetLowering::DAGCombinerInfo &DCI,
24495                                 const X86Subtarget *Subtarget) {
24496   if (DCI.isBeforeLegalizeOps())
24497     return SDValue();
24498
24499   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24500     return R;
24501
24502   SDValue N0 = N->getOperand(0);
24503   SDValue N1 = N->getOperand(1);
24504   EVT VT = N->getValueType(0);
24505
24506   // look for psign/blend
24507   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24508     if (!Subtarget->hasSSSE3() ||
24509         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24510       return SDValue();
24511
24512     // Canonicalize pandn to RHS
24513     if (N0.getOpcode() == X86ISD::ANDNP)
24514       std::swap(N0, N1);
24515     // or (and (m, y), (pandn m, x))
24516     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24517       SDValue Mask = N1.getOperand(0);
24518       SDValue X    = N1.getOperand(1);
24519       SDValue Y;
24520       if (N0.getOperand(0) == Mask)
24521         Y = N0.getOperand(1);
24522       if (N0.getOperand(1) == Mask)
24523         Y = N0.getOperand(0);
24524
24525       // Check to see if the mask appeared in both the AND and ANDNP and
24526       if (!Y.getNode())
24527         return SDValue();
24528
24529       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24530       // Look through mask bitcast.
24531       if (Mask.getOpcode() == ISD::BITCAST)
24532         Mask = Mask.getOperand(0);
24533       if (X.getOpcode() == ISD::BITCAST)
24534         X = X.getOperand(0);
24535       if (Y.getOpcode() == ISD::BITCAST)
24536         Y = Y.getOperand(0);
24537
24538       EVT MaskVT = Mask.getValueType();
24539
24540       // Validate that the Mask operand is a vector sra node.
24541       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24542       // there is no psrai.b
24543       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24544       unsigned SraAmt = ~0;
24545       if (Mask.getOpcode() == ISD::SRA) {
24546         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24547           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24548             SraAmt = AmtConst->getZExtValue();
24549       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24550         SDValue SraC = Mask.getOperand(1);
24551         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24552       }
24553       if ((SraAmt + 1) != EltBits)
24554         return SDValue();
24555
24556       SDLoc DL(N);
24557
24558       // Now we know we at least have a plendvb with the mask val.  See if
24559       // we can form a psignb/w/d.
24560       // psign = x.type == y.type == mask.type && y = sub(0, x);
24561       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24562           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24563           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24564         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24565                "Unsupported VT for PSIGN");
24566         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24567         return DAG.getBitcast(VT, Mask);
24568       }
24569       // PBLENDVB only available on SSE 4.1
24570       if (!Subtarget->hasSSE41())
24571         return SDValue();
24572
24573       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24574
24575       X = DAG.getBitcast(BlendVT, X);
24576       Y = DAG.getBitcast(BlendVT, Y);
24577       Mask = DAG.getBitcast(BlendVT, Mask);
24578       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24579       return DAG.getBitcast(VT, Mask);
24580     }
24581   }
24582
24583   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24584     return SDValue();
24585
24586   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24587   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24588
24589   // SHLD/SHRD instructions have lower register pressure, but on some
24590   // platforms they have higher latency than the equivalent
24591   // series of shifts/or that would otherwise be generated.
24592   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24593   // have higher latencies and we are not optimizing for size.
24594   if (!OptForSize && Subtarget->isSHLDSlow())
24595     return SDValue();
24596
24597   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24598     std::swap(N0, N1);
24599   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24600     return SDValue();
24601   if (!N0.hasOneUse() || !N1.hasOneUse())
24602     return SDValue();
24603
24604   SDValue ShAmt0 = N0.getOperand(1);
24605   if (ShAmt0.getValueType() != MVT::i8)
24606     return SDValue();
24607   SDValue ShAmt1 = N1.getOperand(1);
24608   if (ShAmt1.getValueType() != MVT::i8)
24609     return SDValue();
24610   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24611     ShAmt0 = ShAmt0.getOperand(0);
24612   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24613     ShAmt1 = ShAmt1.getOperand(0);
24614
24615   SDLoc DL(N);
24616   unsigned Opc = X86ISD::SHLD;
24617   SDValue Op0 = N0.getOperand(0);
24618   SDValue Op1 = N1.getOperand(0);
24619   if (ShAmt0.getOpcode() == ISD::SUB) {
24620     Opc = X86ISD::SHRD;
24621     std::swap(Op0, Op1);
24622     std::swap(ShAmt0, ShAmt1);
24623   }
24624
24625   unsigned Bits = VT.getSizeInBits();
24626   if (ShAmt1.getOpcode() == ISD::SUB) {
24627     SDValue Sum = ShAmt1.getOperand(0);
24628     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24629       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24630       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24631         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24632       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24633         return DAG.getNode(Opc, DL, VT,
24634                            Op0, Op1,
24635                            DAG.getNode(ISD::TRUNCATE, DL,
24636                                        MVT::i8, ShAmt0));
24637     }
24638   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24639     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24640     if (ShAmt0C &&
24641         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24642       return DAG.getNode(Opc, DL, VT,
24643                          N0.getOperand(0), N1.getOperand(0),
24644                          DAG.getNode(ISD::TRUNCATE, DL,
24645                                        MVT::i8, ShAmt0));
24646   }
24647
24648   return SDValue();
24649 }
24650
24651 // Generate NEG and CMOV for integer abs.
24652 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24653   EVT VT = N->getValueType(0);
24654
24655   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24656   // 8-bit integer abs to NEG and CMOV.
24657   if (VT.isInteger() && VT.getSizeInBits() == 8)
24658     return SDValue();
24659
24660   SDValue N0 = N->getOperand(0);
24661   SDValue N1 = N->getOperand(1);
24662   SDLoc DL(N);
24663
24664   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24665   // and change it to SUB and CMOV.
24666   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24667       N0.getOpcode() == ISD::ADD &&
24668       N0.getOperand(1) == N1 &&
24669       N1.getOpcode() == ISD::SRA &&
24670       N1.getOperand(0) == N0.getOperand(0))
24671     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24672       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24673         // Generate SUB & CMOV.
24674         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24675                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24676
24677         SDValue Ops[] = { N0.getOperand(0), Neg,
24678                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24679                           SDValue(Neg.getNode(), 1) };
24680         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24681       }
24682   return SDValue();
24683 }
24684
24685 // Try to turn tests against the signbit in the form of:
24686 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24687 // into:
24688 //   SETGT(X, -1)
24689 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24690   // This is only worth doing if the output type is i8.
24691   if (N->getValueType(0) != MVT::i8)
24692     return SDValue();
24693
24694   SDValue N0 = N->getOperand(0);
24695   SDValue N1 = N->getOperand(1);
24696
24697   // We should be performing an xor against a truncated shift.
24698   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24699     return SDValue();
24700
24701   // Make sure we are performing an xor against one.
24702   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24703     return SDValue();
24704
24705   // SetCC on x86 zero extends so only act on this if it's a logical shift.
24706   SDValue Shift = N0.getOperand(0);
24707   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24708     return SDValue();
24709
24710   // Make sure we are truncating from one of i16, i32 or i64.
24711   EVT ShiftTy = Shift.getValueType();
24712   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24713     return SDValue();
24714
24715   // Make sure the shift amount extracts the sign bit.
24716   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24717       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24718     return SDValue();
24719
24720   // Create a greater-than comparison against -1.
24721   // N.B. Using SETGE against 0 works but we want a canonical looking
24722   // comparison, using SETGT matches up with what TranslateX86CC.
24723   SDLoc DL(N);
24724   SDValue ShiftOp = Shift.getOperand(0);
24725   EVT ShiftOpTy = ShiftOp.getValueType();
24726   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24727                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24728   return Cond;
24729 }
24730
24731 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24732                                  TargetLowering::DAGCombinerInfo &DCI,
24733                                  const X86Subtarget *Subtarget) {
24734   if (DCI.isBeforeLegalizeOps())
24735     return SDValue();
24736
24737   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24738     return RV;
24739
24740   if (Subtarget->hasCMov())
24741     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24742       return RV;
24743
24744   return SDValue();
24745 }
24746
24747 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24748 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24749                                   TargetLowering::DAGCombinerInfo &DCI,
24750                                   const X86Subtarget *Subtarget) {
24751   LoadSDNode *Ld = cast<LoadSDNode>(N);
24752   EVT RegVT = Ld->getValueType(0);
24753   EVT MemVT = Ld->getMemoryVT();
24754   SDLoc dl(Ld);
24755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24756
24757   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24758   // into two 16-byte operations.
24759   ISD::LoadExtType Ext = Ld->getExtensionType();
24760   bool Fast;
24761   unsigned AddressSpace = Ld->getAddressSpace();
24762   unsigned Alignment = Ld->getAlignment();
24763   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24764       Ext == ISD::NON_EXTLOAD &&
24765       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24766                              AddressSpace, Alignment, &Fast) && !Fast) {
24767     unsigned NumElems = RegVT.getVectorNumElements();
24768     if (NumElems < 2)
24769       return SDValue();
24770
24771     SDValue Ptr = Ld->getBasePtr();
24772     SDValue Increment =
24773         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24774
24775     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24776                                   NumElems/2);
24777     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24778                                 Ld->getPointerInfo(), Ld->isVolatile(),
24779                                 Ld->isNonTemporal(), Ld->isInvariant(),
24780                                 Alignment);
24781     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24782     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24783                                 Ld->getPointerInfo(), Ld->isVolatile(),
24784                                 Ld->isNonTemporal(), Ld->isInvariant(),
24785                                 std::min(16U, Alignment));
24786     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24787                              Load1.getValue(1),
24788                              Load2.getValue(1));
24789
24790     SDValue NewVec = DAG.getUNDEF(RegVT);
24791     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24792     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24793     return DCI.CombineTo(N, NewVec, TF, true);
24794   }
24795
24796   return SDValue();
24797 }
24798
24799 /// PerformMLOADCombine - Resolve extending loads
24800 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24801                                    TargetLowering::DAGCombinerInfo &DCI,
24802                                    const X86Subtarget *Subtarget) {
24803   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24804   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24805     return SDValue();
24806
24807   EVT VT = Mld->getValueType(0);
24808   unsigned NumElems = VT.getVectorNumElements();
24809   EVT LdVT = Mld->getMemoryVT();
24810   SDLoc dl(Mld);
24811
24812   assert(LdVT != VT && "Cannot extend to the same type");
24813   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24814   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24815   // From, To sizes and ElemCount must be pow of two
24816   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24817     "Unexpected size for extending masked load");
24818
24819   unsigned SizeRatio  = ToSz / FromSz;
24820   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24821
24822   // Create a type on which we perform the shuffle
24823   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24824           LdVT.getScalarType(), NumElems*SizeRatio);
24825   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24826
24827   // Convert Src0 value
24828   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24829   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24830     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24831     for (unsigned i = 0; i != NumElems; ++i)
24832       ShuffleVec[i] = i * SizeRatio;
24833
24834     // Can't shuffle using an illegal type.
24835     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
24836            "WideVecVT should be legal");
24837     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24838                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24839   }
24840   // Prepare the new mask
24841   SDValue NewMask;
24842   SDValue Mask = Mld->getMask();
24843   if (Mask.getValueType() == VT) {
24844     // Mask and original value have the same type
24845     NewMask = DAG.getBitcast(WideVecVT, Mask);
24846     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24847     for (unsigned i = 0; i != NumElems; ++i)
24848       ShuffleVec[i] = i * SizeRatio;
24849     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24850       ShuffleVec[i] = NumElems*SizeRatio;
24851     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24852                                    DAG.getConstant(0, dl, WideVecVT),
24853                                    &ShuffleVec[0]);
24854   }
24855   else {
24856     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24857     unsigned WidenNumElts = NumElems*SizeRatio;
24858     unsigned MaskNumElts = VT.getVectorNumElements();
24859     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24860                                      WidenNumElts);
24861
24862     unsigned NumConcat = WidenNumElts / MaskNumElts;
24863     SmallVector<SDValue, 16> Ops(NumConcat);
24864     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24865     Ops[0] = Mask;
24866     for (unsigned i = 1; i != NumConcat; ++i)
24867       Ops[i] = ZeroVal;
24868
24869     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24870   }
24871
24872   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24873                                      Mld->getBasePtr(), NewMask, WideSrc0,
24874                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24875                                      ISD::NON_EXTLOAD);
24876   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24877   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24878 }
24879 /// PerformMSTORECombine - Resolve truncating stores
24880 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24881                                     const X86Subtarget *Subtarget) {
24882   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24883   if (!Mst->isTruncatingStore())
24884     return SDValue();
24885
24886   EVT VT = Mst->getValue().getValueType();
24887   unsigned NumElems = VT.getVectorNumElements();
24888   EVT StVT = Mst->getMemoryVT();
24889   SDLoc dl(Mst);
24890
24891   assert(StVT != VT && "Cannot truncate to the same type");
24892   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24893   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24894
24895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24896
24897   // The truncating store is legal in some cases. For example
24898   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24899   // are designated for truncate store.
24900   // In this case we don't need any further transformations.
24901   if (TLI.isTruncStoreLegal(VT, StVT))
24902     return SDValue();
24903
24904   // From, To sizes and ElemCount must be pow of two
24905   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24906     "Unexpected size for truncating masked store");
24907   // We are going to use the original vector elt for storing.
24908   // Accumulated smaller vector elements must be a multiple of the store size.
24909   assert (((NumElems * FromSz) % ToSz) == 0 &&
24910           "Unexpected ratio for truncating masked store");
24911
24912   unsigned SizeRatio  = FromSz / ToSz;
24913   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24914
24915   // Create a type on which we perform the shuffle
24916   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24917           StVT.getScalarType(), NumElems*SizeRatio);
24918
24919   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24920
24921   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24922   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24923   for (unsigned i = 0; i != NumElems; ++i)
24924     ShuffleVec[i] = i * SizeRatio;
24925
24926   // Can't shuffle using an illegal type.
24927   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
24928          "WideVecVT should be legal");
24929
24930   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24931                                         DAG.getUNDEF(WideVecVT),
24932                                         &ShuffleVec[0]);
24933
24934   SDValue NewMask;
24935   SDValue Mask = Mst->getMask();
24936   if (Mask.getValueType() == VT) {
24937     // Mask and original value have the same type
24938     NewMask = DAG.getBitcast(WideVecVT, Mask);
24939     for (unsigned i = 0; i != NumElems; ++i)
24940       ShuffleVec[i] = i * SizeRatio;
24941     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24942       ShuffleVec[i] = NumElems*SizeRatio;
24943     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24944                                    DAG.getConstant(0, dl, WideVecVT),
24945                                    &ShuffleVec[0]);
24946   }
24947   else {
24948     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24949     unsigned WidenNumElts = NumElems*SizeRatio;
24950     unsigned MaskNumElts = VT.getVectorNumElements();
24951     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24952                                      WidenNumElts);
24953
24954     unsigned NumConcat = WidenNumElts / MaskNumElts;
24955     SmallVector<SDValue, 16> Ops(NumConcat);
24956     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24957     Ops[0] = Mask;
24958     for (unsigned i = 1; i != NumConcat; ++i)
24959       Ops[i] = ZeroVal;
24960
24961     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24962   }
24963
24964   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24965                             NewMask, StVT, Mst->getMemOperand(), false);
24966 }
24967 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24968 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24969                                    const X86Subtarget *Subtarget) {
24970   StoreSDNode *St = cast<StoreSDNode>(N);
24971   EVT VT = St->getValue().getValueType();
24972   EVT StVT = St->getMemoryVT();
24973   SDLoc dl(St);
24974   SDValue StoredVal = St->getOperand(1);
24975   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24976
24977   // If we are saving a concatenation of two XMM registers and 32-byte stores
24978   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24979   bool Fast;
24980   unsigned AddressSpace = St->getAddressSpace();
24981   unsigned Alignment = St->getAlignment();
24982   if (VT.is256BitVector() && StVT == VT &&
24983       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24984                              AddressSpace, Alignment, &Fast) && !Fast) {
24985     unsigned NumElems = VT.getVectorNumElements();
24986     if (NumElems < 2)
24987       return SDValue();
24988
24989     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24990     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24991
24992     SDValue Stride =
24993         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24994     SDValue Ptr0 = St->getBasePtr();
24995     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24996
24997     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24998                                 St->getPointerInfo(), St->isVolatile(),
24999                                 St->isNonTemporal(), Alignment);
25000     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25001                                 St->getPointerInfo(), St->isVolatile(),
25002                                 St->isNonTemporal(),
25003                                 std::min(16U, Alignment));
25004     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25005   }
25006
25007   // Optimize trunc store (of multiple scalars) to shuffle and store.
25008   // First, pack all of the elements in one place. Next, store to memory
25009   // in fewer chunks.
25010   if (St->isTruncatingStore() && VT.isVector()) {
25011     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25012     unsigned NumElems = VT.getVectorNumElements();
25013     assert(StVT != VT && "Cannot truncate to the same type");
25014     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25015     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25016
25017     // The truncating store is legal in some cases. For example
25018     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25019     // are designated for truncate store.
25020     // In this case we don't need any further transformations.
25021     if (TLI.isTruncStoreLegal(VT, StVT))
25022       return SDValue();
25023
25024     // From, To sizes and ElemCount must be pow of two
25025     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25026     // We are going to use the original vector elt for storing.
25027     // Accumulated smaller vector elements must be a multiple of the store size.
25028     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25029
25030     unsigned SizeRatio  = FromSz / ToSz;
25031
25032     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25033
25034     // Create a type on which we perform the shuffle
25035     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25036             StVT.getScalarType(), NumElems*SizeRatio);
25037
25038     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25039
25040     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25041     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25042     for (unsigned i = 0; i != NumElems; ++i)
25043       ShuffleVec[i] = i * SizeRatio;
25044
25045     // Can't shuffle using an illegal type.
25046     if (!TLI.isTypeLegal(WideVecVT))
25047       return SDValue();
25048
25049     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25050                                          DAG.getUNDEF(WideVecVT),
25051                                          &ShuffleVec[0]);
25052     // At this point all of the data is stored at the bottom of the
25053     // register. We now need to save it to mem.
25054
25055     // Find the largest store unit
25056     MVT StoreType = MVT::i8;
25057     for (MVT Tp : MVT::integer_valuetypes()) {
25058       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25059         StoreType = Tp;
25060     }
25061
25062     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25063     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25064         (64 <= NumElems * ToSz))
25065       StoreType = MVT::f64;
25066
25067     // Bitcast the original vector into a vector of store-size units
25068     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25069             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25070     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25071     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25072     SmallVector<SDValue, 8> Chains;
25073     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25074                                         TLI.getPointerTy(DAG.getDataLayout()));
25075     SDValue Ptr = St->getBasePtr();
25076
25077     // Perform one or more big stores into memory.
25078     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25079       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25080                                    StoreType, ShuffWide,
25081                                    DAG.getIntPtrConstant(i, dl));
25082       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25083                                 St->getPointerInfo(), St->isVolatile(),
25084                                 St->isNonTemporal(), St->getAlignment());
25085       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25086       Chains.push_back(Ch);
25087     }
25088
25089     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25090   }
25091
25092   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25093   // the FP state in cases where an emms may be missing.
25094   // A preferable solution to the general problem is to figure out the right
25095   // places to insert EMMS.  This qualifies as a quick hack.
25096
25097   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25098   if (VT.getSizeInBits() != 64)
25099     return SDValue();
25100
25101   const Function *F = DAG.getMachineFunction().getFunction();
25102   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25103   bool F64IsLegal =
25104       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25105   if ((VT.isVector() ||
25106        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25107       isa<LoadSDNode>(St->getValue()) &&
25108       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25109       St->getChain().hasOneUse() && !St->isVolatile()) {
25110     SDNode* LdVal = St->getValue().getNode();
25111     LoadSDNode *Ld = nullptr;
25112     int TokenFactorIndex = -1;
25113     SmallVector<SDValue, 8> Ops;
25114     SDNode* ChainVal = St->getChain().getNode();
25115     // Must be a store of a load.  We currently handle two cases:  the load
25116     // is a direct child, and it's under an intervening TokenFactor.  It is
25117     // possible to dig deeper under nested TokenFactors.
25118     if (ChainVal == LdVal)
25119       Ld = cast<LoadSDNode>(St->getChain());
25120     else if (St->getValue().hasOneUse() &&
25121              ChainVal->getOpcode() == ISD::TokenFactor) {
25122       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25123         if (ChainVal->getOperand(i).getNode() == LdVal) {
25124           TokenFactorIndex = i;
25125           Ld = cast<LoadSDNode>(St->getValue());
25126         } else
25127           Ops.push_back(ChainVal->getOperand(i));
25128       }
25129     }
25130
25131     if (!Ld || !ISD::isNormalLoad(Ld))
25132       return SDValue();
25133
25134     // If this is not the MMX case, i.e. we are just turning i64 load/store
25135     // into f64 load/store, avoid the transformation if there are multiple
25136     // uses of the loaded value.
25137     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25138       return SDValue();
25139
25140     SDLoc LdDL(Ld);
25141     SDLoc StDL(N);
25142     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25143     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25144     // pair instead.
25145     if (Subtarget->is64Bit() || F64IsLegal) {
25146       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25147       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25148                                   Ld->getPointerInfo(), Ld->isVolatile(),
25149                                   Ld->isNonTemporal(), Ld->isInvariant(),
25150                                   Ld->getAlignment());
25151       SDValue NewChain = NewLd.getValue(1);
25152       if (TokenFactorIndex != -1) {
25153         Ops.push_back(NewChain);
25154         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25155       }
25156       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25157                           St->getPointerInfo(),
25158                           St->isVolatile(), St->isNonTemporal(),
25159                           St->getAlignment());
25160     }
25161
25162     // Otherwise, lower to two pairs of 32-bit loads / stores.
25163     SDValue LoAddr = Ld->getBasePtr();
25164     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25165                                  DAG.getConstant(4, LdDL, MVT::i32));
25166
25167     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25168                                Ld->getPointerInfo(),
25169                                Ld->isVolatile(), Ld->isNonTemporal(),
25170                                Ld->isInvariant(), Ld->getAlignment());
25171     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25172                                Ld->getPointerInfo().getWithOffset(4),
25173                                Ld->isVolatile(), Ld->isNonTemporal(),
25174                                Ld->isInvariant(),
25175                                MinAlign(Ld->getAlignment(), 4));
25176
25177     SDValue NewChain = LoLd.getValue(1);
25178     if (TokenFactorIndex != -1) {
25179       Ops.push_back(LoLd);
25180       Ops.push_back(HiLd);
25181       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25182     }
25183
25184     LoAddr = St->getBasePtr();
25185     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25186                          DAG.getConstant(4, StDL, MVT::i32));
25187
25188     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25189                                 St->getPointerInfo(),
25190                                 St->isVolatile(), St->isNonTemporal(),
25191                                 St->getAlignment());
25192     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25193                                 St->getPointerInfo().getWithOffset(4),
25194                                 St->isVolatile(),
25195                                 St->isNonTemporal(),
25196                                 MinAlign(St->getAlignment(), 4));
25197     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25198   }
25199
25200   // This is similar to the above case, but here we handle a scalar 64-bit
25201   // integer store that is extracted from a vector on a 32-bit target.
25202   // If we have SSE2, then we can treat it like a floating-point double
25203   // to get past legalization. The execution dependencies fixup pass will
25204   // choose the optimal machine instruction for the store if this really is
25205   // an integer or v2f32 rather than an f64.
25206   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25207       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25208     SDValue OldExtract = St->getOperand(1);
25209     SDValue ExtOp0 = OldExtract.getOperand(0);
25210     unsigned VecSize = ExtOp0.getValueSizeInBits();
25211     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25212     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25213     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25214                                      BitCast, OldExtract.getOperand(1));
25215     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25216                         St->getPointerInfo(), St->isVolatile(),
25217                         St->isNonTemporal(), St->getAlignment());
25218   }
25219
25220   return SDValue();
25221 }
25222
25223 /// Return 'true' if this vector operation is "horizontal"
25224 /// and return the operands for the horizontal operation in LHS and RHS.  A
25225 /// horizontal operation performs the binary operation on successive elements
25226 /// of its first operand, then on successive elements of its second operand,
25227 /// returning the resulting values in a vector.  For example, if
25228 ///   A = < float a0, float a1, float a2, float a3 >
25229 /// and
25230 ///   B = < float b0, float b1, float b2, float b3 >
25231 /// then the result of doing a horizontal operation on A and B is
25232 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25233 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25234 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25235 /// set to A, RHS to B, and the routine returns 'true'.
25236 /// Note that the binary operation should have the property that if one of the
25237 /// operands is UNDEF then the result is UNDEF.
25238 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25239   // Look for the following pattern: if
25240   //   A = < float a0, float a1, float a2, float a3 >
25241   //   B = < float b0, float b1, float b2, float b3 >
25242   // and
25243   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25244   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25245   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25246   // which is A horizontal-op B.
25247
25248   // At least one of the operands should be a vector shuffle.
25249   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25250       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25251     return false;
25252
25253   MVT VT = LHS.getSimpleValueType();
25254
25255   assert((VT.is128BitVector() || VT.is256BitVector()) &&
25256          "Unsupported vector type for horizontal add/sub");
25257
25258   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25259   // operate independently on 128-bit lanes.
25260   unsigned NumElts = VT.getVectorNumElements();
25261   unsigned NumLanes = VT.getSizeInBits()/128;
25262   unsigned NumLaneElts = NumElts / NumLanes;
25263   assert((NumLaneElts % 2 == 0) &&
25264          "Vector type should have an even number of elements in each lane");
25265   unsigned HalfLaneElts = NumLaneElts/2;
25266
25267   // View LHS in the form
25268   //   LHS = VECTOR_SHUFFLE A, B, LMask
25269   // If LHS is not a shuffle then pretend it is the shuffle
25270   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25271   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25272   // type VT.
25273   SDValue A, B;
25274   SmallVector<int, 16> LMask(NumElts);
25275   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25276     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25277       A = LHS.getOperand(0);
25278     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25279       B = LHS.getOperand(1);
25280     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25281     std::copy(Mask.begin(), Mask.end(), LMask.begin());
25282   } else {
25283     if (LHS.getOpcode() != ISD::UNDEF)
25284       A = LHS;
25285     for (unsigned i = 0; i != NumElts; ++i)
25286       LMask[i] = i;
25287   }
25288
25289   // Likewise, view RHS in the form
25290   //   RHS = VECTOR_SHUFFLE C, D, RMask
25291   SDValue C, D;
25292   SmallVector<int, 16> RMask(NumElts);
25293   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25294     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25295       C = RHS.getOperand(0);
25296     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25297       D = RHS.getOperand(1);
25298     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25299     std::copy(Mask.begin(), Mask.end(), RMask.begin());
25300   } else {
25301     if (RHS.getOpcode() != ISD::UNDEF)
25302       C = RHS;
25303     for (unsigned i = 0; i != NumElts; ++i)
25304       RMask[i] = i;
25305   }
25306
25307   // Check that the shuffles are both shuffling the same vectors.
25308   if (!(A == C && B == D) && !(A == D && B == C))
25309     return false;
25310
25311   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25312   if (!A.getNode() && !B.getNode())
25313     return false;
25314
25315   // If A and B occur in reverse order in RHS, then "swap" them (which means
25316   // rewriting the mask).
25317   if (A != C)
25318     ShuffleVectorSDNode::commuteMask(RMask);
25319
25320   // At this point LHS and RHS are equivalent to
25321   //   LHS = VECTOR_SHUFFLE A, B, LMask
25322   //   RHS = VECTOR_SHUFFLE A, B, RMask
25323   // Check that the masks correspond to performing a horizontal operation.
25324   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25325     for (unsigned i = 0; i != NumLaneElts; ++i) {
25326       int LIdx = LMask[i+l], RIdx = RMask[i+l];
25327
25328       // Ignore any UNDEF components.
25329       if (LIdx < 0 || RIdx < 0 ||
25330           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25331           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25332         continue;
25333
25334       // Check that successive elements are being operated on.  If not, this is
25335       // not a horizontal operation.
25336       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25337       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25338       if (!(LIdx == Index && RIdx == Index + 1) &&
25339           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25340         return false;
25341     }
25342   }
25343
25344   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25345   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25346   return true;
25347 }
25348
25349 /// Do target-specific dag combines on floating point adds.
25350 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25351                                   const X86Subtarget *Subtarget) {
25352   EVT VT = N->getValueType(0);
25353   SDValue LHS = N->getOperand(0);
25354   SDValue RHS = N->getOperand(1);
25355
25356   // Try to synthesize horizontal adds from adds of shuffles.
25357   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25358        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25359       isHorizontalBinOp(LHS, RHS, true))
25360     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25361   return SDValue();
25362 }
25363
25364 /// Do target-specific dag combines on floating point subs.
25365 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25366                                   const X86Subtarget *Subtarget) {
25367   EVT VT = N->getValueType(0);
25368   SDValue LHS = N->getOperand(0);
25369   SDValue RHS = N->getOperand(1);
25370
25371   // Try to synthesize horizontal subs from subs of shuffles.
25372   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25373        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25374       isHorizontalBinOp(LHS, RHS, false))
25375     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25376   return SDValue();
25377 }
25378
25379 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25380 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25381                                  const X86Subtarget *Subtarget) {
25382   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25383
25384   // F[X]OR(0.0, x) -> x
25385   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25386     if (C->getValueAPF().isPosZero())
25387       return N->getOperand(1);
25388
25389   // F[X]OR(x, 0.0) -> x
25390   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25391     if (C->getValueAPF().isPosZero())
25392       return N->getOperand(0);
25393
25394   EVT VT = N->getValueType(0);
25395   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25396     SDLoc dl(N);
25397     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25398     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25399
25400     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25401     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25402     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25403     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25404     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25405   }
25406   return SDValue();
25407 }
25408
25409 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25410 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25411   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25412
25413   // Only perform optimizations if UnsafeMath is used.
25414   if (!DAG.getTarget().Options.UnsafeFPMath)
25415     return SDValue();
25416
25417   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25418   // into FMINC and FMAXC, which are Commutative operations.
25419   unsigned NewOp = 0;
25420   switch (N->getOpcode()) {
25421     default: llvm_unreachable("unknown opcode");
25422     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
25423     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
25424   }
25425
25426   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25427                      N->getOperand(0), N->getOperand(1));
25428 }
25429
25430 /// Do target-specific dag combines on X86ISD::FAND nodes.
25431 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25432   // FAND(0.0, x) -> 0.0
25433   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25434     if (C->getValueAPF().isPosZero())
25435       return N->getOperand(0);
25436
25437   // FAND(x, 0.0) -> 0.0
25438   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25439     if (C->getValueAPF().isPosZero())
25440       return N->getOperand(1);
25441
25442   return SDValue();
25443 }
25444
25445 /// Do target-specific dag combines on X86ISD::FANDN nodes
25446 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25447   // FANDN(0.0, x) -> x
25448   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25449     if (C->getValueAPF().isPosZero())
25450       return N->getOperand(1);
25451
25452   // FANDN(x, 0.0) -> 0.0
25453   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25454     if (C->getValueAPF().isPosZero())
25455       return N->getOperand(1);
25456
25457   return SDValue();
25458 }
25459
25460 static SDValue PerformBTCombine(SDNode *N,
25461                                 SelectionDAG &DAG,
25462                                 TargetLowering::DAGCombinerInfo &DCI) {
25463   // BT ignores high bits in the bit index operand.
25464   SDValue Op1 = N->getOperand(1);
25465   if (Op1.hasOneUse()) {
25466     unsigned BitWidth = Op1.getValueSizeInBits();
25467     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25468     APInt KnownZero, KnownOne;
25469     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25470                                           !DCI.isBeforeLegalizeOps());
25471     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25472     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25473         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25474       DCI.CommitTargetLoweringOpt(TLO);
25475   }
25476   return SDValue();
25477 }
25478
25479 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25480   SDValue Op = N->getOperand(0);
25481   if (Op.getOpcode() == ISD::BITCAST)
25482     Op = Op.getOperand(0);
25483   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25484   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25485       VT.getVectorElementType().getSizeInBits() ==
25486       OpVT.getVectorElementType().getSizeInBits()) {
25487     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25488   }
25489   return SDValue();
25490 }
25491
25492 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25493                                                const X86Subtarget *Subtarget) {
25494   EVT VT = N->getValueType(0);
25495   if (!VT.isVector())
25496     return SDValue();
25497
25498   SDValue N0 = N->getOperand(0);
25499   SDValue N1 = N->getOperand(1);
25500   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25501   SDLoc dl(N);
25502
25503   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25504   // both SSE and AVX2 since there is no sign-extended shift right
25505   // operation on a vector with 64-bit elements.
25506   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25507   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25508   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25509       N0.getOpcode() == ISD::SIGN_EXTEND)) {
25510     SDValue N00 = N0.getOperand(0);
25511
25512     // EXTLOAD has a better solution on AVX2,
25513     // it may be replaced with X86ISD::VSEXT node.
25514     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25515       if (!ISD::isNormalLoad(N00.getNode()))
25516         return SDValue();
25517
25518     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25519         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25520                                   N00, N1);
25521       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25522     }
25523   }
25524   return SDValue();
25525 }
25526
25527 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25528                                   TargetLowering::DAGCombinerInfo &DCI,
25529                                   const X86Subtarget *Subtarget) {
25530   SDValue N0 = N->getOperand(0);
25531   EVT VT = N->getValueType(0);
25532   EVT SVT = VT.getScalarType();
25533   EVT InVT = N0.getValueType();
25534   EVT InSVT = InVT.getScalarType();
25535   SDLoc DL(N);
25536
25537   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25538   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25539   // This exposes the sext to the sdivrem lowering, so that it directly extends
25540   // from AH (which we otherwise need to do contortions to access).
25541   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25542       InVT == MVT::i8 && VT == MVT::i32) {
25543     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25544     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25545                             N0.getOperand(0), N0.getOperand(1));
25546     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25547     return R.getValue(1);
25548   }
25549
25550   if (!DCI.isBeforeLegalizeOps()) {
25551     if (InVT == MVT::i1) {
25552       SDValue Zero = DAG.getConstant(0, DL, VT);
25553       SDValue AllOnes =
25554         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25555       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25556     }
25557     return SDValue();
25558   }
25559
25560   if (VT.isVector() && Subtarget->hasSSE2()) {
25561     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25562       EVT InVT = N.getValueType();
25563       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25564                                    Size / InVT.getScalarSizeInBits());
25565       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25566                                     DAG.getUNDEF(InVT));
25567       Opnds[0] = N;
25568       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25569     };
25570
25571     // If target-size is less than 128-bits, extend to a type that would extend
25572     // to 128 bits, extend that and extract the original target vector.
25573     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25574         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25575         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25576       unsigned Scale = 128 / VT.getSizeInBits();
25577       EVT ExVT =
25578           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25579       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25580       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25581       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25582                          DAG.getIntPtrConstant(0, DL));
25583     }
25584
25585     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25586     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25587     if (VT.getSizeInBits() == 128 &&
25588         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25589         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25590       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25591       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25592     }
25593
25594     // On pre-AVX2 targets, split into 128-bit nodes of
25595     // ISD::SIGN_EXTEND_VECTOR_INREG.
25596     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25597         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25598         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25599       unsigned NumVecs = VT.getSizeInBits() / 128;
25600       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25601       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25602       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25603
25604       SmallVector<SDValue, 8> Opnds;
25605       for (unsigned i = 0, Offset = 0; i != NumVecs;
25606            ++i, Offset += NumSubElts) {
25607         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25608                                      DAG.getIntPtrConstant(Offset, DL));
25609         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25610         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25611         Opnds.push_back(SrcVec);
25612       }
25613       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25614     }
25615   }
25616
25617   if (!Subtarget->hasFp256())
25618     return SDValue();
25619
25620   if (VT.isVector() && VT.getSizeInBits() == 256)
25621     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25622       return R;
25623
25624   return SDValue();
25625 }
25626
25627 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25628                                  const X86Subtarget* Subtarget) {
25629   SDLoc dl(N);
25630   EVT VT = N->getValueType(0);
25631
25632   // Let legalize expand this if it isn't a legal type yet.
25633   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25634     return SDValue();
25635
25636   EVT ScalarVT = VT.getScalarType();
25637   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25638       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25639        !Subtarget->hasAVX512()))
25640     return SDValue();
25641
25642   SDValue A = N->getOperand(0);
25643   SDValue B = N->getOperand(1);
25644   SDValue C = N->getOperand(2);
25645
25646   bool NegA = (A.getOpcode() == ISD::FNEG);
25647   bool NegB = (B.getOpcode() == ISD::FNEG);
25648   bool NegC = (C.getOpcode() == ISD::FNEG);
25649
25650   // Negative multiplication when NegA xor NegB
25651   bool NegMul = (NegA != NegB);
25652   if (NegA)
25653     A = A.getOperand(0);
25654   if (NegB)
25655     B = B.getOperand(0);
25656   if (NegC)
25657     C = C.getOperand(0);
25658
25659   unsigned Opcode;
25660   if (!NegMul)
25661     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25662   else
25663     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25664
25665   return DAG.getNode(Opcode, dl, VT, A, B, C);
25666 }
25667
25668 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25669                                   TargetLowering::DAGCombinerInfo &DCI,
25670                                   const X86Subtarget *Subtarget) {
25671   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25672   //           (and (i32 x86isd::setcc_carry), 1)
25673   // This eliminates the zext. This transformation is necessary because
25674   // ISD::SETCC is always legalized to i8.
25675   SDLoc dl(N);
25676   SDValue N0 = N->getOperand(0);
25677   EVT VT = N->getValueType(0);
25678
25679   if (N0.getOpcode() == ISD::AND &&
25680       N0.hasOneUse() &&
25681       N0.getOperand(0).hasOneUse()) {
25682     SDValue N00 = N0.getOperand(0);
25683     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25684       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25685       if (!C || C->getZExtValue() != 1)
25686         return SDValue();
25687       return DAG.getNode(ISD::AND, dl, VT,
25688                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25689                                      N00.getOperand(0), N00.getOperand(1)),
25690                          DAG.getConstant(1, dl, VT));
25691     }
25692   }
25693
25694   if (N0.getOpcode() == ISD::TRUNCATE &&
25695       N0.hasOneUse() &&
25696       N0.getOperand(0).hasOneUse()) {
25697     SDValue N00 = N0.getOperand(0);
25698     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25699       return DAG.getNode(ISD::AND, dl, VT,
25700                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25701                                      N00.getOperand(0), N00.getOperand(1)),
25702                          DAG.getConstant(1, dl, VT));
25703     }
25704   }
25705
25706   if (VT.is256BitVector())
25707     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25708       return R;
25709
25710   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25711   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25712   // This exposes the zext to the udivrem lowering, so that it directly extends
25713   // from AH (which we otherwise need to do contortions to access).
25714   if (N0.getOpcode() == ISD::UDIVREM &&
25715       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25716       (VT == MVT::i32 || VT == MVT::i64)) {
25717     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25718     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25719                             N0.getOperand(0), N0.getOperand(1));
25720     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25721     return R.getValue(1);
25722   }
25723
25724   return SDValue();
25725 }
25726
25727 // Optimize x == -y --> x+y == 0
25728 //          x != -y --> x+y != 0
25729 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25730                                       const X86Subtarget* Subtarget) {
25731   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25732   SDValue LHS = N->getOperand(0);
25733   SDValue RHS = N->getOperand(1);
25734   EVT VT = N->getValueType(0);
25735   SDLoc DL(N);
25736
25737   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25738     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25739       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25740         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25741                                    LHS.getOperand(1));
25742         return DAG.getSetCC(DL, N->getValueType(0), addV,
25743                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25744       }
25745   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25746     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25747       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25748         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25749                                    RHS.getOperand(1));
25750         return DAG.getSetCC(DL, N->getValueType(0), addV,
25751                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25752       }
25753
25754   if (VT.getScalarType() == MVT::i1 &&
25755       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25756     bool IsSEXT0 =
25757         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25758         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25759     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25760
25761     if (!IsSEXT0 || !IsVZero1) {
25762       // Swap the operands and update the condition code.
25763       std::swap(LHS, RHS);
25764       CC = ISD::getSetCCSwappedOperands(CC);
25765
25766       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25767                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25768       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25769     }
25770
25771     if (IsSEXT0 && IsVZero1) {
25772       assert(VT == LHS.getOperand(0).getValueType() &&
25773              "Uexpected operand type");
25774       if (CC == ISD::SETGT)
25775         return DAG.getConstant(0, DL, VT);
25776       if (CC == ISD::SETLE)
25777         return DAG.getConstant(1, DL, VT);
25778       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25779         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25780
25781       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25782              "Unexpected condition code!");
25783       return LHS.getOperand(0);
25784     }
25785   }
25786
25787   return SDValue();
25788 }
25789
25790 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25791                                          SelectionDAG &DAG) {
25792   SDLoc dl(Load);
25793   MVT VT = Load->getSimpleValueType(0);
25794   MVT EVT = VT.getVectorElementType();
25795   SDValue Addr = Load->getOperand(1);
25796   SDValue NewAddr = DAG.getNode(
25797       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25798       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25799                       Addr.getSimpleValueType()));
25800
25801   SDValue NewLoad =
25802       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25803                   DAG.getMachineFunction().getMachineMemOperand(
25804                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25805   return NewLoad;
25806 }
25807
25808 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25809                                       const X86Subtarget *Subtarget) {
25810   SDLoc dl(N);
25811   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25812   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25813          "X86insertps is only defined for v4x32");
25814
25815   SDValue Ld = N->getOperand(1);
25816   if (MayFoldLoad(Ld)) {
25817     // Extract the countS bits from the immediate so we can get the proper
25818     // address when narrowing the vector load to a specific element.
25819     // When the second source op is a memory address, insertps doesn't use
25820     // countS and just gets an f32 from that address.
25821     unsigned DestIndex =
25822         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25823
25824     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25825
25826     // Create this as a scalar to vector to match the instruction pattern.
25827     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25828     // countS bits are ignored when loading from memory on insertps, which
25829     // means we don't need to explicitly set them to 0.
25830     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25831                        LoadScalarToVector, N->getOperand(2));
25832   }
25833   return SDValue();
25834 }
25835
25836 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25837   SDValue V0 = N->getOperand(0);
25838   SDValue V1 = N->getOperand(1);
25839   SDLoc DL(N);
25840   EVT VT = N->getValueType(0);
25841
25842   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25843   // operands and changing the mask to 1. This saves us a bunch of
25844   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25845   // x86InstrInfo knows how to commute this back after instruction selection
25846   // if it would help register allocation.
25847
25848   // TODO: If optimizing for size or a processor that doesn't suffer from
25849   // partial register update stalls, this should be transformed into a MOVSD
25850   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25851
25852   if (VT == MVT::v2f64)
25853     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25854       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25855         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25856         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25857       }
25858
25859   return SDValue();
25860 }
25861
25862 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25863 // as "sbb reg,reg", since it can be extended without zext and produces
25864 // an all-ones bit which is more useful than 0/1 in some cases.
25865 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25866                                MVT VT) {
25867   if (VT == MVT::i8)
25868     return DAG.getNode(ISD::AND, DL, VT,
25869                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25870                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25871                                    EFLAGS),
25872                        DAG.getConstant(1, DL, VT));
25873   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25874   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25875                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25876                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25877                                  EFLAGS));
25878 }
25879
25880 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25881 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25882                                    TargetLowering::DAGCombinerInfo &DCI,
25883                                    const X86Subtarget *Subtarget) {
25884   SDLoc DL(N);
25885   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25886   SDValue EFLAGS = N->getOperand(1);
25887
25888   if (CC == X86::COND_A) {
25889     // Try to convert COND_A into COND_B in an attempt to facilitate
25890     // materializing "setb reg".
25891     //
25892     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25893     // cannot take an immediate as its first operand.
25894     //
25895     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25896         EFLAGS.getValueType().isInteger() &&
25897         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25898       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25899                                    EFLAGS.getNode()->getVTList(),
25900                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25901       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25902       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25903     }
25904   }
25905
25906   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25907   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25908   // cases.
25909   if (CC == X86::COND_B)
25910     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25911
25912   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25913     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25914     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25915   }
25916
25917   return SDValue();
25918 }
25919
25920 // Optimize branch condition evaluation.
25921 //
25922 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25923                                     TargetLowering::DAGCombinerInfo &DCI,
25924                                     const X86Subtarget *Subtarget) {
25925   SDLoc DL(N);
25926   SDValue Chain = N->getOperand(0);
25927   SDValue Dest = N->getOperand(1);
25928   SDValue EFLAGS = N->getOperand(3);
25929   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25930
25931   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25932     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25933     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25934                        Flags);
25935   }
25936
25937   return SDValue();
25938 }
25939
25940 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25941                                                          SelectionDAG &DAG) {
25942   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25943   // optimize away operation when it's from a constant.
25944   //
25945   // The general transformation is:
25946   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25947   //       AND(VECTOR_CMP(x,y), constant2)
25948   //    constant2 = UNARYOP(constant)
25949
25950   // Early exit if this isn't a vector operation, the operand of the
25951   // unary operation isn't a bitwise AND, or if the sizes of the operations
25952   // aren't the same.
25953   EVT VT = N->getValueType(0);
25954   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25955       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25956       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25957     return SDValue();
25958
25959   // Now check that the other operand of the AND is a constant. We could
25960   // make the transformation for non-constant splats as well, but it's unclear
25961   // that would be a benefit as it would not eliminate any operations, just
25962   // perform one more step in scalar code before moving to the vector unit.
25963   if (BuildVectorSDNode *BV =
25964           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25965     // Bail out if the vector isn't a constant.
25966     if (!BV->isConstant())
25967       return SDValue();
25968
25969     // Everything checks out. Build up the new and improved node.
25970     SDLoc DL(N);
25971     EVT IntVT = BV->getValueType(0);
25972     // Create a new constant of the appropriate type for the transformed
25973     // DAG.
25974     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25975     // The AND node needs bitcasts to/from an integer vector type around it.
25976     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25977     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25978                                  N->getOperand(0)->getOperand(0), MaskConst);
25979     SDValue Res = DAG.getBitcast(VT, NewAnd);
25980     return Res;
25981   }
25982
25983   return SDValue();
25984 }
25985
25986 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25987                                         const X86Subtarget *Subtarget) {
25988   SDValue Op0 = N->getOperand(0);
25989   EVT VT = N->getValueType(0);
25990   EVT InVT = Op0.getValueType();
25991   EVT InSVT = InVT.getScalarType();
25992   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25993
25994   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25995   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25996   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25997     SDLoc dl(N);
25998     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25999                                  InVT.getVectorNumElements());
26000     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26001
26002     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26003       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26004
26005     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26006   }
26007
26008   return SDValue();
26009 }
26010
26011 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26012                                         const X86Subtarget *Subtarget) {
26013   // First try to optimize away the conversion entirely when it's
26014   // conditionally from a constant. Vectors only.
26015   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26016     return Res;
26017
26018   // Now move on to more general possibilities.
26019   SDValue Op0 = N->getOperand(0);
26020   EVT VT = N->getValueType(0);
26021   EVT InVT = Op0.getValueType();
26022   EVT InSVT = InVT.getScalarType();
26023
26024   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26025   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26026   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26027     SDLoc dl(N);
26028     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26029                                  InVT.getVectorNumElements());
26030     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26031     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26032   }
26033
26034   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26035   // a 32-bit target where SSE doesn't support i64->FP operations.
26036   if (Op0.getOpcode() == ISD::LOAD) {
26037     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26038     EVT LdVT = Ld->getValueType(0);
26039
26040     // This transformation is not supported if the result type is f16
26041     if (VT == MVT::f16)
26042       return SDValue();
26043
26044     if (!Ld->isVolatile() && !VT.isVector() &&
26045         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26046         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26047       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26048           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26049       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26050       return FILDChain;
26051     }
26052   }
26053   return SDValue();
26054 }
26055
26056 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26057 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26058                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26059   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26060   // the result is either zero or one (depending on the input carry bit).
26061   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26062   if (X86::isZeroNode(N->getOperand(0)) &&
26063       X86::isZeroNode(N->getOperand(1)) &&
26064       // We don't have a good way to replace an EFLAGS use, so only do this when
26065       // dead right now.
26066       SDValue(N, 1).use_empty()) {
26067     SDLoc DL(N);
26068     EVT VT = N->getValueType(0);
26069     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26070     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26071                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26072                                            DAG.getConstant(X86::COND_B, DL,
26073                                                            MVT::i8),
26074                                            N->getOperand(2)),
26075                                DAG.getConstant(1, DL, VT));
26076     return DCI.CombineTo(N, Res1, CarryOut);
26077   }
26078
26079   return SDValue();
26080 }
26081
26082 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26083 //      (add Y, (setne X, 0)) -> sbb -1, Y
26084 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26085 //      (sub (setne X, 0), Y) -> adc -1, Y
26086 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26087   SDLoc DL(N);
26088
26089   // Look through ZExts.
26090   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26091   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26092     return SDValue();
26093
26094   SDValue SetCC = Ext.getOperand(0);
26095   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26096     return SDValue();
26097
26098   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26099   if (CC != X86::COND_E && CC != X86::COND_NE)
26100     return SDValue();
26101
26102   SDValue Cmp = SetCC.getOperand(1);
26103   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26104       !X86::isZeroNode(Cmp.getOperand(1)) ||
26105       !Cmp.getOperand(0).getValueType().isInteger())
26106     return SDValue();
26107
26108   SDValue CmpOp0 = Cmp.getOperand(0);
26109   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26110                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26111
26112   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26113   if (CC == X86::COND_NE)
26114     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26115                        DL, OtherVal.getValueType(), OtherVal,
26116                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26117                        NewCmp);
26118   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26119                      DL, OtherVal.getValueType(), OtherVal,
26120                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26121 }
26122
26123 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26124 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26125                                  const X86Subtarget *Subtarget) {
26126   EVT VT = N->getValueType(0);
26127   SDValue Op0 = N->getOperand(0);
26128   SDValue Op1 = N->getOperand(1);
26129
26130   // Try to synthesize horizontal adds from adds of shuffles.
26131   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26132        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26133       isHorizontalBinOp(Op0, Op1, true))
26134     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26135
26136   return OptimizeConditionalInDecrement(N, DAG);
26137 }
26138
26139 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26140                                  const X86Subtarget *Subtarget) {
26141   SDValue Op0 = N->getOperand(0);
26142   SDValue Op1 = N->getOperand(1);
26143
26144   // X86 can't encode an immediate LHS of a sub. See if we can push the
26145   // negation into a preceding instruction.
26146   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26147     // If the RHS of the sub is a XOR with one use and a constant, invert the
26148     // immediate. Then add one to the LHS of the sub so we can turn
26149     // X-Y -> X+~Y+1, saving one register.
26150     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26151         isa<ConstantSDNode>(Op1.getOperand(1))) {
26152       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26153       EVT VT = Op0.getValueType();
26154       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26155                                    Op1.getOperand(0),
26156                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26157       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26158                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26159     }
26160   }
26161
26162   // Try to synthesize horizontal adds from adds of shuffles.
26163   EVT VT = N->getValueType(0);
26164   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26165        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26166       isHorizontalBinOp(Op0, Op1, true))
26167     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26168
26169   return OptimizeConditionalInDecrement(N, DAG);
26170 }
26171
26172 /// performVZEXTCombine - Performs build vector combines
26173 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26174                                    TargetLowering::DAGCombinerInfo &DCI,
26175                                    const X86Subtarget *Subtarget) {
26176   SDLoc DL(N);
26177   MVT VT = N->getSimpleValueType(0);
26178   SDValue Op = N->getOperand(0);
26179   MVT OpVT = Op.getSimpleValueType();
26180   MVT OpEltVT = OpVT.getVectorElementType();
26181   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26182
26183   // (vzext (bitcast (vzext (x)) -> (vzext x)
26184   SDValue V = Op;
26185   while (V.getOpcode() == ISD::BITCAST)
26186     V = V.getOperand(0);
26187
26188   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26189     MVT InnerVT = V.getSimpleValueType();
26190     MVT InnerEltVT = InnerVT.getVectorElementType();
26191
26192     // If the element sizes match exactly, we can just do one larger vzext. This
26193     // is always an exact type match as vzext operates on integer types.
26194     if (OpEltVT == InnerEltVT) {
26195       assert(OpVT == InnerVT && "Types must match for vzext!");
26196       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26197     }
26198
26199     // The only other way we can combine them is if only a single element of the
26200     // inner vzext is used in the input to the outer vzext.
26201     if (InnerEltVT.getSizeInBits() < InputBits)
26202       return SDValue();
26203
26204     // In this case, the inner vzext is completely dead because we're going to
26205     // only look at bits inside of the low element. Just do the outer vzext on
26206     // a bitcast of the input to the inner.
26207     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26208   }
26209
26210   // Check if we can bypass extracting and re-inserting an element of an input
26211   // vector. Essentially:
26212   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26213   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26214       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26215       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26216     SDValue ExtractedV = V.getOperand(0);
26217     SDValue OrigV = ExtractedV.getOperand(0);
26218     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26219       if (ExtractIdx->getZExtValue() == 0) {
26220         MVT OrigVT = OrigV.getSimpleValueType();
26221         // Extract a subvector if necessary...
26222         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26223           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26224           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26225                                     OrigVT.getVectorNumElements() / Ratio);
26226           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26227                               DAG.getIntPtrConstant(0, DL));
26228         }
26229         Op = DAG.getBitcast(OpVT, OrigV);
26230         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26231       }
26232   }
26233
26234   return SDValue();
26235 }
26236
26237 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26238                                              DAGCombinerInfo &DCI) const {
26239   SelectionDAG &DAG = DCI.DAG;
26240   switch (N->getOpcode()) {
26241   default: break;
26242   case ISD::EXTRACT_VECTOR_ELT:
26243     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26244   case ISD::VSELECT:
26245   case ISD::SELECT:
26246   case X86ISD::SHRUNKBLEND:
26247     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26248   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
26249   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26250   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
26251   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
26252   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
26253   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
26254   case ISD::SHL:
26255   case ISD::SRA:
26256   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
26257   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
26258   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
26259   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
26260   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
26261   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26262   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
26263   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
26264   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26265   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26266   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
26267   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
26268   case X86ISD::FXOR:
26269   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
26270   case X86ISD::FMIN:
26271   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
26272   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
26273   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
26274   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
26275   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
26276   case ISD::ANY_EXTEND:
26277   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
26278   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
26279   case ISD::SIGN_EXTEND_INREG:
26280     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26281   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
26282   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26283   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26284   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
26285   case X86ISD::SHUFP:       // Handle all target specific shuffles
26286   case X86ISD::PALIGNR:
26287   case X86ISD::UNPCKH:
26288   case X86ISD::UNPCKL:
26289   case X86ISD::MOVHLPS:
26290   case X86ISD::MOVLHPS:
26291   case X86ISD::PSHUFB:
26292   case X86ISD::PSHUFD:
26293   case X86ISD::PSHUFHW:
26294   case X86ISD::PSHUFLW:
26295   case X86ISD::MOVSS:
26296   case X86ISD::MOVSD:
26297   case X86ISD::VPERMILPI:
26298   case X86ISD::VPERM2X128:
26299   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26300   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
26301   case X86ISD::INSERTPS: {
26302     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26303       return PerformINSERTPSCombine(N, DAG, Subtarget);
26304     break;
26305   }
26306   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
26307   }
26308
26309   return SDValue();
26310 }
26311
26312 /// isTypeDesirableForOp - Return true if the target has native support for
26313 /// the specified value type and it is 'desirable' to use the type for the
26314 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26315 /// instruction encodings are longer and some i16 instructions are slow.
26316 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26317   if (!isTypeLegal(VT))
26318     return false;
26319   if (VT != MVT::i16)
26320     return true;
26321
26322   switch (Opc) {
26323   default:
26324     return true;
26325   case ISD::LOAD:
26326   case ISD::SIGN_EXTEND:
26327   case ISD::ZERO_EXTEND:
26328   case ISD::ANY_EXTEND:
26329   case ISD::SHL:
26330   case ISD::SRL:
26331   case ISD::SUB:
26332   case ISD::ADD:
26333   case ISD::MUL:
26334   case ISD::AND:
26335   case ISD::OR:
26336   case ISD::XOR:
26337     return false;
26338   }
26339 }
26340
26341 /// IsDesirableToPromoteOp - This method query the target whether it is
26342 /// beneficial for dag combiner to promote the specified node. If true, it
26343 /// should return the desired promotion type by reference.
26344 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26345   EVT VT = Op.getValueType();
26346   if (VT != MVT::i16)
26347     return false;
26348
26349   bool Promote = false;
26350   bool Commute = false;
26351   switch (Op.getOpcode()) {
26352   default: break;
26353   case ISD::LOAD: {
26354     LoadSDNode *LD = cast<LoadSDNode>(Op);
26355     // If the non-extending load has a single use and it's not live out, then it
26356     // might be folded.
26357     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26358                                                      Op.hasOneUse()*/) {
26359       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26360              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26361         // The only case where we'd want to promote LOAD (rather then it being
26362         // promoted as an operand is when it's only use is liveout.
26363         if (UI->getOpcode() != ISD::CopyToReg)
26364           return false;
26365       }
26366     }
26367     Promote = true;
26368     break;
26369   }
26370   case ISD::SIGN_EXTEND:
26371   case ISD::ZERO_EXTEND:
26372   case ISD::ANY_EXTEND:
26373     Promote = true;
26374     break;
26375   case ISD::SHL:
26376   case ISD::SRL: {
26377     SDValue N0 = Op.getOperand(0);
26378     // Look out for (store (shl (load), x)).
26379     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26380       return false;
26381     Promote = true;
26382     break;
26383   }
26384   case ISD::ADD:
26385   case ISD::MUL:
26386   case ISD::AND:
26387   case ISD::OR:
26388   case ISD::XOR:
26389     Commute = true;
26390     // fallthrough
26391   case ISD::SUB: {
26392     SDValue N0 = Op.getOperand(0);
26393     SDValue N1 = Op.getOperand(1);
26394     if (!Commute && MayFoldLoad(N1))
26395       return false;
26396     // Avoid disabling potential load folding opportunities.
26397     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26398       return false;
26399     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26400       return false;
26401     Promote = true;
26402   }
26403   }
26404
26405   PVT = MVT::i32;
26406   return Promote;
26407 }
26408
26409 //===----------------------------------------------------------------------===//
26410 //                           X86 Inline Assembly Support
26411 //===----------------------------------------------------------------------===//
26412
26413 // Helper to match a string separated by whitespace.
26414 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26415   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26416
26417   for (StringRef Piece : Pieces) {
26418     if (!S.startswith(Piece)) // Check if the piece matches.
26419       return false;
26420
26421     S = S.substr(Piece.size());
26422     StringRef::size_type Pos = S.find_first_not_of(" \t");
26423     if (Pos == 0) // We matched a prefix.
26424       return false;
26425
26426     S = S.substr(Pos);
26427   }
26428
26429   return S.empty();
26430 }
26431
26432 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26433
26434   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26435     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26436         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26437         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26438
26439       if (AsmPieces.size() == 3)
26440         return true;
26441       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26442         return true;
26443     }
26444   }
26445   return false;
26446 }
26447
26448 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26449   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26450
26451   std::string AsmStr = IA->getAsmString();
26452
26453   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26454   if (!Ty || Ty->getBitWidth() % 16 != 0)
26455     return false;
26456
26457   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26458   SmallVector<StringRef, 4> AsmPieces;
26459   SplitString(AsmStr, AsmPieces, ";\n");
26460
26461   switch (AsmPieces.size()) {
26462   default: return false;
26463   case 1:
26464     // FIXME: this should verify that we are targeting a 486 or better.  If not,
26465     // we will turn this bswap into something that will be lowered to logical
26466     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
26467     // lower so don't worry about this.
26468     // bswap $0
26469     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26470         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26471         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26472         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26473         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26474         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26475       // No need to check constraints, nothing other than the equivalent of
26476       // "=r,0" would be valid here.
26477       return IntrinsicLowering::LowerToByteSwap(CI);
26478     }
26479
26480     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
26481     if (CI->getType()->isIntegerTy(16) &&
26482         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26483         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26484          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26485       AsmPieces.clear();
26486       StringRef ConstraintsStr = IA->getConstraintString();
26487       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26488       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26489       if (clobbersFlagRegisters(AsmPieces))
26490         return IntrinsicLowering::LowerToByteSwap(CI);
26491     }
26492     break;
26493   case 3:
26494     if (CI->getType()->isIntegerTy(32) &&
26495         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26496         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26497         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26498         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26499       AsmPieces.clear();
26500       StringRef ConstraintsStr = IA->getConstraintString();
26501       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26502       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26503       if (clobbersFlagRegisters(AsmPieces))
26504         return IntrinsicLowering::LowerToByteSwap(CI);
26505     }
26506
26507     if (CI->getType()->isIntegerTy(64)) {
26508       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26509       if (Constraints.size() >= 2 &&
26510           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26511           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26512         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
26513         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26514             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26515             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26516           return IntrinsicLowering::LowerToByteSwap(CI);
26517       }
26518     }
26519     break;
26520   }
26521   return false;
26522 }
26523
26524 /// getConstraintType - Given a constraint letter, return the type of
26525 /// constraint it is for this target.
26526 X86TargetLowering::ConstraintType
26527 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26528   if (Constraint.size() == 1) {
26529     switch (Constraint[0]) {
26530     case 'R':
26531     case 'q':
26532     case 'Q':
26533     case 'f':
26534     case 't':
26535     case 'u':
26536     case 'y':
26537     case 'x':
26538     case 'Y':
26539     case 'l':
26540       return C_RegisterClass;
26541     case 'a':
26542     case 'b':
26543     case 'c':
26544     case 'd':
26545     case 'S':
26546     case 'D':
26547     case 'A':
26548       return C_Register;
26549     case 'I':
26550     case 'J':
26551     case 'K':
26552     case 'L':
26553     case 'M':
26554     case 'N':
26555     case 'G':
26556     case 'C':
26557     case 'e':
26558     case 'Z':
26559       return C_Other;
26560     default:
26561       break;
26562     }
26563   }
26564   return TargetLowering::getConstraintType(Constraint);
26565 }
26566
26567 /// Examine constraint type and operand type and determine a weight value.
26568 /// This object must already have been set up with the operand type
26569 /// and the current alternative constraint selected.
26570 TargetLowering::ConstraintWeight
26571   X86TargetLowering::getSingleConstraintMatchWeight(
26572     AsmOperandInfo &info, const char *constraint) const {
26573   ConstraintWeight weight = CW_Invalid;
26574   Value *CallOperandVal = info.CallOperandVal;
26575     // If we don't have a value, we can't do a match,
26576     // but allow it at the lowest weight.
26577   if (!CallOperandVal)
26578     return CW_Default;
26579   Type *type = CallOperandVal->getType();
26580   // Look at the constraint type.
26581   switch (*constraint) {
26582   default:
26583     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26584   case 'R':
26585   case 'q':
26586   case 'Q':
26587   case 'a':
26588   case 'b':
26589   case 'c':
26590   case 'd':
26591   case 'S':
26592   case 'D':
26593   case 'A':
26594     if (CallOperandVal->getType()->isIntegerTy())
26595       weight = CW_SpecificReg;
26596     break;
26597   case 'f':
26598   case 't':
26599   case 'u':
26600     if (type->isFloatingPointTy())
26601       weight = CW_SpecificReg;
26602     break;
26603   case 'y':
26604     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26605       weight = CW_SpecificReg;
26606     break;
26607   case 'x':
26608   case 'Y':
26609     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26610         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26611       weight = CW_Register;
26612     break;
26613   case 'I':
26614     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26615       if (C->getZExtValue() <= 31)
26616         weight = CW_Constant;
26617     }
26618     break;
26619   case 'J':
26620     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26621       if (C->getZExtValue() <= 63)
26622         weight = CW_Constant;
26623     }
26624     break;
26625   case 'K':
26626     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26627       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26628         weight = CW_Constant;
26629     }
26630     break;
26631   case 'L':
26632     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26633       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26634         weight = CW_Constant;
26635     }
26636     break;
26637   case 'M':
26638     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26639       if (C->getZExtValue() <= 3)
26640         weight = CW_Constant;
26641     }
26642     break;
26643   case 'N':
26644     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26645       if (C->getZExtValue() <= 0xff)
26646         weight = CW_Constant;
26647     }
26648     break;
26649   case 'G':
26650   case 'C':
26651     if (isa<ConstantFP>(CallOperandVal)) {
26652       weight = CW_Constant;
26653     }
26654     break;
26655   case 'e':
26656     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26657       if ((C->getSExtValue() >= -0x80000000LL) &&
26658           (C->getSExtValue() <= 0x7fffffffLL))
26659         weight = CW_Constant;
26660     }
26661     break;
26662   case 'Z':
26663     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26664       if (C->getZExtValue() <= 0xffffffff)
26665         weight = CW_Constant;
26666     }
26667     break;
26668   }
26669   return weight;
26670 }
26671
26672 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26673 /// with another that has more specific requirements based on the type of the
26674 /// corresponding operand.
26675 const char *X86TargetLowering::
26676 LowerXConstraint(EVT ConstraintVT) const {
26677   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26678   // 'f' like normal targets.
26679   if (ConstraintVT.isFloatingPoint()) {
26680     if (Subtarget->hasSSE2())
26681       return "Y";
26682     if (Subtarget->hasSSE1())
26683       return "x";
26684   }
26685
26686   return TargetLowering::LowerXConstraint(ConstraintVT);
26687 }
26688
26689 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26690 /// vector.  If it is invalid, don't add anything to Ops.
26691 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26692                                                      std::string &Constraint,
26693                                                      std::vector<SDValue>&Ops,
26694                                                      SelectionDAG &DAG) const {
26695   SDValue Result;
26696
26697   // Only support length 1 constraints for now.
26698   if (Constraint.length() > 1) return;
26699
26700   char ConstraintLetter = Constraint[0];
26701   switch (ConstraintLetter) {
26702   default: break;
26703   case 'I':
26704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26705       if (C->getZExtValue() <= 31) {
26706         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26707                                        Op.getValueType());
26708         break;
26709       }
26710     }
26711     return;
26712   case 'J':
26713     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26714       if (C->getZExtValue() <= 63) {
26715         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26716                                        Op.getValueType());
26717         break;
26718       }
26719     }
26720     return;
26721   case 'K':
26722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26723       if (isInt<8>(C->getSExtValue())) {
26724         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26725                                        Op.getValueType());
26726         break;
26727       }
26728     }
26729     return;
26730   case 'L':
26731     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26732       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26733           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26734         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26735                                        Op.getValueType());
26736         break;
26737       }
26738     }
26739     return;
26740   case 'M':
26741     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26742       if (C->getZExtValue() <= 3) {
26743         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26744                                        Op.getValueType());
26745         break;
26746       }
26747     }
26748     return;
26749   case 'N':
26750     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26751       if (C->getZExtValue() <= 255) {
26752         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26753                                        Op.getValueType());
26754         break;
26755       }
26756     }
26757     return;
26758   case 'O':
26759     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26760       if (C->getZExtValue() <= 127) {
26761         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26762                                        Op.getValueType());
26763         break;
26764       }
26765     }
26766     return;
26767   case 'e': {
26768     // 32-bit signed value
26769     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26770       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26771                                            C->getSExtValue())) {
26772         // Widen to 64 bits here to get it sign extended.
26773         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26774         break;
26775       }
26776     // FIXME gcc accepts some relocatable values here too, but only in certain
26777     // memory models; it's complicated.
26778     }
26779     return;
26780   }
26781   case 'Z': {
26782     // 32-bit unsigned value
26783     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26784       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26785                                            C->getZExtValue())) {
26786         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26787                                        Op.getValueType());
26788         break;
26789       }
26790     }
26791     // FIXME gcc accepts some relocatable values here too, but only in certain
26792     // memory models; it's complicated.
26793     return;
26794   }
26795   case 'i': {
26796     // Literal immediates are always ok.
26797     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26798       // Widen to 64 bits here to get it sign extended.
26799       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26800       break;
26801     }
26802
26803     // In any sort of PIC mode addresses need to be computed at runtime by
26804     // adding in a register or some sort of table lookup.  These can't
26805     // be used as immediates.
26806     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26807       return;
26808
26809     // If we are in non-pic codegen mode, we allow the address of a global (with
26810     // an optional displacement) to be used with 'i'.
26811     GlobalAddressSDNode *GA = nullptr;
26812     int64_t Offset = 0;
26813
26814     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26815     while (1) {
26816       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26817         Offset += GA->getOffset();
26818         break;
26819       } else if (Op.getOpcode() == ISD::ADD) {
26820         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26821           Offset += C->getZExtValue();
26822           Op = Op.getOperand(0);
26823           continue;
26824         }
26825       } else if (Op.getOpcode() == ISD::SUB) {
26826         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26827           Offset += -C->getZExtValue();
26828           Op = Op.getOperand(0);
26829           continue;
26830         }
26831       }
26832
26833       // Otherwise, this isn't something we can handle, reject it.
26834       return;
26835     }
26836
26837     const GlobalValue *GV = GA->getGlobal();
26838     // If we require an extra load to get this address, as in PIC mode, we
26839     // can't accept it.
26840     if (isGlobalStubReference(
26841             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26842       return;
26843
26844     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26845                                         GA->getValueType(0), Offset);
26846     break;
26847   }
26848   }
26849
26850   if (Result.getNode()) {
26851     Ops.push_back(Result);
26852     return;
26853   }
26854   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26855 }
26856
26857 std::pair<unsigned, const TargetRegisterClass *>
26858 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26859                                                 StringRef Constraint,
26860                                                 MVT VT) const {
26861   // First, see if this is a constraint that directly corresponds to an LLVM
26862   // register class.
26863   if (Constraint.size() == 1) {
26864     // GCC Constraint Letters
26865     switch (Constraint[0]) {
26866     default: break;
26867       // TODO: Slight differences here in allocation order and leaving
26868       // RIP in the class. Do they matter any more here than they do
26869       // in the normal allocation?
26870     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26871       if (Subtarget->is64Bit()) {
26872         if (VT == MVT::i32 || VT == MVT::f32)
26873           return std::make_pair(0U, &X86::GR32RegClass);
26874         if (VT == MVT::i16)
26875           return std::make_pair(0U, &X86::GR16RegClass);
26876         if (VT == MVT::i8 || VT == MVT::i1)
26877           return std::make_pair(0U, &X86::GR8RegClass);
26878         if (VT == MVT::i64 || VT == MVT::f64)
26879           return std::make_pair(0U, &X86::GR64RegClass);
26880         break;
26881       }
26882       // 32-bit fallthrough
26883     case 'Q':   // Q_REGS
26884       if (VT == MVT::i32 || VT == MVT::f32)
26885         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26886       if (VT == MVT::i16)
26887         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26888       if (VT == MVT::i8 || VT == MVT::i1)
26889         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26890       if (VT == MVT::i64)
26891         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26892       break;
26893     case 'r':   // GENERAL_REGS
26894     case 'l':   // INDEX_REGS
26895       if (VT == MVT::i8 || VT == MVT::i1)
26896         return std::make_pair(0U, &X86::GR8RegClass);
26897       if (VT == MVT::i16)
26898         return std::make_pair(0U, &X86::GR16RegClass);
26899       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26900         return std::make_pair(0U, &X86::GR32RegClass);
26901       return std::make_pair(0U, &X86::GR64RegClass);
26902     case 'R':   // LEGACY_REGS
26903       if (VT == MVT::i8 || VT == MVT::i1)
26904         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26905       if (VT == MVT::i16)
26906         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26907       if (VT == MVT::i32 || !Subtarget->is64Bit())
26908         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26909       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26910     case 'f':  // FP Stack registers.
26911       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26912       // value to the correct fpstack register class.
26913       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26914         return std::make_pair(0U, &X86::RFP32RegClass);
26915       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26916         return std::make_pair(0U, &X86::RFP64RegClass);
26917       return std::make_pair(0U, &X86::RFP80RegClass);
26918     case 'y':   // MMX_REGS if MMX allowed.
26919       if (!Subtarget->hasMMX()) break;
26920       return std::make_pair(0U, &X86::VR64RegClass);
26921     case 'Y':   // SSE_REGS if SSE2 allowed
26922       if (!Subtarget->hasSSE2()) break;
26923       // FALL THROUGH.
26924     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26925       if (!Subtarget->hasSSE1()) break;
26926
26927       switch (VT.SimpleTy) {
26928       default: break;
26929       // Scalar SSE types.
26930       case MVT::f32:
26931       case MVT::i32:
26932         return std::make_pair(0U, &X86::FR32RegClass);
26933       case MVT::f64:
26934       case MVT::i64:
26935         return std::make_pair(0U, &X86::FR64RegClass);
26936       // Vector types.
26937       case MVT::v16i8:
26938       case MVT::v8i16:
26939       case MVT::v4i32:
26940       case MVT::v2i64:
26941       case MVT::v4f32:
26942       case MVT::v2f64:
26943         return std::make_pair(0U, &X86::VR128RegClass);
26944       // AVX types.
26945       case MVT::v32i8:
26946       case MVT::v16i16:
26947       case MVT::v8i32:
26948       case MVT::v4i64:
26949       case MVT::v8f32:
26950       case MVT::v4f64:
26951         return std::make_pair(0U, &X86::VR256RegClass);
26952       case MVT::v8f64:
26953       case MVT::v16f32:
26954       case MVT::v16i32:
26955       case MVT::v8i64:
26956         return std::make_pair(0U, &X86::VR512RegClass);
26957       }
26958       break;
26959     }
26960   }
26961
26962   // Use the default implementation in TargetLowering to convert the register
26963   // constraint into a member of a register class.
26964   std::pair<unsigned, const TargetRegisterClass*> Res;
26965   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26966
26967   // Not found as a standard register?
26968   if (!Res.second) {
26969     // Map st(0) -> st(7) -> ST0
26970     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26971         tolower(Constraint[1]) == 's' &&
26972         tolower(Constraint[2]) == 't' &&
26973         Constraint[3] == '(' &&
26974         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26975         Constraint[5] == ')' &&
26976         Constraint[6] == '}') {
26977
26978       Res.first = X86::FP0+Constraint[4]-'0';
26979       Res.second = &X86::RFP80RegClass;
26980       return Res;
26981     }
26982
26983     // GCC allows "st(0)" to be called just plain "st".
26984     if (StringRef("{st}").equals_lower(Constraint)) {
26985       Res.first = X86::FP0;
26986       Res.second = &X86::RFP80RegClass;
26987       return Res;
26988     }
26989
26990     // flags -> EFLAGS
26991     if (StringRef("{flags}").equals_lower(Constraint)) {
26992       Res.first = X86::EFLAGS;
26993       Res.second = &X86::CCRRegClass;
26994       return Res;
26995     }
26996
26997     // 'A' means EAX + EDX.
26998     if (Constraint == "A") {
26999       Res.first = X86::EAX;
27000       Res.second = &X86::GR32_ADRegClass;
27001       return Res;
27002     }
27003     return Res;
27004   }
27005
27006   // Otherwise, check to see if this is a register class of the wrong value
27007   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27008   // turn into {ax},{dx}.
27009   // MVT::Other is used to specify clobber names.
27010   if (Res.second->hasType(VT) || VT == MVT::Other)
27011     return Res;   // Correct type already, nothing to do.
27012
27013   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27014   // return "eax". This should even work for things like getting 64bit integer
27015   // registers when given an f64 type.
27016   const TargetRegisterClass *Class = Res.second;
27017   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27018       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27019     unsigned Size = VT.getSizeInBits();
27020     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27021                                   : Size == 16 ? MVT::i16
27022                                   : Size == 32 ? MVT::i32
27023                                   : Size == 64 ? MVT::i64
27024                                   : MVT::Other;
27025     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27026     if (DestReg > 0) {
27027       Res.first = DestReg;
27028       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27029                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27030                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27031                  : &X86::GR64RegClass;
27032       assert(Res.second->contains(Res.first) && "Register in register class");
27033     } else {
27034       // No register found/type mismatch.
27035       Res.first = 0;
27036       Res.second = nullptr;
27037     }
27038   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27039              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27040              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27041              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27042              Class == &X86::VR512RegClass) {
27043     // Handle references to XMM physical registers that got mapped into the
27044     // wrong class.  This can happen with constraints like {xmm0} where the
27045     // target independent register mapper will just pick the first match it can
27046     // find, ignoring the required type.
27047
27048     if (VT == MVT::f32 || VT == MVT::i32)
27049       Res.second = &X86::FR32RegClass;
27050     else if (VT == MVT::f64 || VT == MVT::i64)
27051       Res.second = &X86::FR64RegClass;
27052     else if (X86::VR128RegClass.hasType(VT))
27053       Res.second = &X86::VR128RegClass;
27054     else if (X86::VR256RegClass.hasType(VT))
27055       Res.second = &X86::VR256RegClass;
27056     else if (X86::VR512RegClass.hasType(VT))
27057       Res.second = &X86::VR512RegClass;
27058     else {
27059       // Type mismatch and not a clobber: Return an error;
27060       Res.first = 0;
27061       Res.second = nullptr;
27062     }
27063   }
27064
27065   return Res;
27066 }
27067
27068 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27069                                             const AddrMode &AM, Type *Ty,
27070                                             unsigned AS) const {
27071   // Scaling factors are not free at all.
27072   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27073   // will take 2 allocations in the out of order engine instead of 1
27074   // for plain addressing mode, i.e. inst (reg1).
27075   // E.g.,
27076   // vaddps (%rsi,%drx), %ymm0, %ymm1
27077   // Requires two allocations (one for the load, one for the computation)
27078   // whereas:
27079   // vaddps (%rsi), %ymm0, %ymm1
27080   // Requires just 1 allocation, i.e., freeing allocations for other operations
27081   // and having less micro operations to execute.
27082   //
27083   // For some X86 architectures, this is even worse because for instance for
27084   // stores, the complex addressing mode forces the instruction to use the
27085   // "load" ports instead of the dedicated "store" port.
27086   // E.g., on Haswell:
27087   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27088   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27089   if (isLegalAddressingMode(DL, AM, Ty, AS))
27090     // Scale represents reg2 * scale, thus account for 1
27091     // as soon as we use a second register.
27092     return AM.Scale != 0;
27093   return -1;
27094 }
27095
27096 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27097   // Integer division on x86 is expensive. However, when aggressively optimizing
27098   // for code size, we prefer to use a div instruction, as it is usually smaller
27099   // than the alternative sequence.
27100   // The exception to this is vector division. Since x86 doesn't have vector
27101   // integer division, leaving the division as-is is a loss even in terms of
27102   // size, because it will have to be scalarized, while the alternative code
27103   // sequence can be performed in vector form.
27104   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27105                                    Attribute::MinSize);
27106   return OptSize && !VT.isVector();
27107 }