AVX-512: Fixed a bug in VPERMT2* intrinsic.
[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/Analysis/LibCallSemantics.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/WinEHFuncInfo.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/MC/MCAsmInfo.h"
47 #include "llvm/MC/MCContext.h"
48 #include "llvm/MC/MCExpr.h"
49 #include "llvm/MC/MCSymbol.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "X86IntrinsicsInfo.h"
56 #include <bitset>
57 #include <numeric>
58 #include <cctype>
59 using namespace llvm;
60
61 #define DEBUG_TYPE "x86-isel"
62
63 STATISTIC(NumTailCalls, "Number of tail calls");
64
65 static cl::opt<bool> ExperimentalVectorWideningLegalization(
66     "x86-experimental-vector-widening-legalization", cl::init(false),
67     cl::desc("Enable an experimental vector type legalization through widening "
68              "rather than promotion."),
69     cl::Hidden);
70
71 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
72                                      const X86Subtarget &STI)
73     : TargetLowering(TM), Subtarget(&STI) {
74   X86ScalarSSEf64 = Subtarget->hasSSE2();
75   X86ScalarSSEf32 = Subtarget->hasSSE1();
76   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77
78   // Set up the TargetLowering object.
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   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
203   // this operation.
204   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
205   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
206
207   if (!Subtarget->useSoftFloat()) {
208     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
209     // are Legal, f80 is custom lowered.
210     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
211     setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
212
213     if (X86ScalarSSEf32) {
214       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
215       // f32 and f64 cases are Legal, f80 case is not
216       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
217     } else {
218       setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
219       setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
220     }
221   } else {
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
223     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Expand);
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Expand);
225   }
226
227   // Handle FP_TO_UINT by promoting the destination to a larger signed
228   // conversion.
229   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
232
233   if (Subtarget->is64Bit()) {
234     if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
235       // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
236       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
237       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Custom);
238     } else {
239       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
240       setOperationAction(ISD::FP_TO_UINT   , MVT::i64  , Expand);
241     }
242   } else if (!Subtarget->useSoftFloat()) {
243     // Since AVX is a superset of SSE3, only check for SSE here.
244     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
245       // Expand FP_TO_UINT into a select.
246       // FIXME: We would like to use a Custom expander here eventually to do
247       // the optimal thing for SSE vs. the default expansion in the legalizer.
248       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
249     else
250       // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
251       // With SSE3 we can use fisttpll to convert to a signed i64; without
252       // SSE, we're stuck with a fistpll.
253       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
254
255     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
256   }
257
258   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
259   if (!X86ScalarSSEf64) {
260     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
261     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
262     if (Subtarget->is64Bit()) {
263       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
264       // Without SSE, i64->f64 goes through memory.
265       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
266     }
267   }
268
269   // Scalar integer divide and remainder are lowered to use operations that
270   // produce two results, to match the available instructions. This exposes
271   // the two-result form to trivial CSE, which is able to combine x/y and x%y
272   // into a single instruction.
273   //
274   // Scalar integer multiply-high is also lowered to use two-result
275   // operations, to match the available instructions. However, plain multiply
276   // (low) operations are left as Legal, as there are single-result
277   // instructions for this in x86. Using the two-result multiply instructions
278   // when both high and low results are needed must be arranged by dagcombine.
279   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
280     setOperationAction(ISD::MULHS, VT, Expand);
281     setOperationAction(ISD::MULHU, VT, Expand);
282     setOperationAction(ISD::SDIV, VT, Expand);
283     setOperationAction(ISD::UDIV, VT, Expand);
284     setOperationAction(ISD::SREM, VT, Expand);
285     setOperationAction(ISD::UREM, VT, Expand);
286
287     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
288     setOperationAction(ISD::ADDC, VT, Custom);
289     setOperationAction(ISD::ADDE, VT, Custom);
290     setOperationAction(ISD::SUBC, VT, Custom);
291     setOperationAction(ISD::SUBE, VT, Custom);
292   }
293
294   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
295   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
296   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
302   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
309   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
310   if (Subtarget->is64Bit())
311     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
314   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
315   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
316
317   if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
318     // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
319     // is. We should promote the value to 64-bits to solve this.
320     // This is what the CRT headers do - `fmodf` is an inline header
321     // function casting to f64 and calling `fmod`.
322     setOperationAction(ISD::FREM           , MVT::f32  , Promote);
323   } else {
324     setOperationAction(ISD::FREM           , MVT::f32  , Expand);
325   }
326
327   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
328   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
329   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
330
331   // Promote the i8 variants and force them on up to i32 which has a shorter
332   // encoding.
333   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
334   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
335   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
336   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
337   if (Subtarget->hasBMI()) {
338     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
339     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
340     if (Subtarget->is64Bit())
341       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
342   } else {
343     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
344     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
345     if (Subtarget->is64Bit())
346       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
347   }
348
349   if (Subtarget->hasLZCNT()) {
350     // When promoting the i8 variants, force them to i32 for a shorter
351     // encoding.
352     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
353     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
355     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
356     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
357     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
358     if (Subtarget->is64Bit())
359       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
360   } else {
361     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
362     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
363     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
364     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
365     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
366     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
367     if (Subtarget->is64Bit()) {
368       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
369       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
370     }
371   }
372
373   // Special handling for half-precision floating point conversions.
374   // If we don't have F16C support, then lower half float conversions
375   // into library calls.
376   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
377     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
378     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
379   }
380
381   // There's never any support for operations beyond MVT::f32.
382   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
383   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
384   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
385   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
386
387   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
388   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
389   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
390   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
391   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
392   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
393
394   if (Subtarget->hasPOPCNT()) {
395     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
396   } else {
397     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
398     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
399     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
400     if (Subtarget->is64Bit())
401       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
402   }
403
404   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
405
406   if (!Subtarget->hasMOVBE())
407     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
408
409   // These should be promoted to a larger select which is supported.
410   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
411   // X86 wants to expand cmov itself.
412   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
413   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
414   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
415   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
416   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
417   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
418   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
419   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
420   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
421   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
422   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
423   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
424   setOperationAction(ISD::SETCCE          , MVT::i8   , Custom);
425   setOperationAction(ISD::SETCCE          , MVT::i16  , Custom);
426   setOperationAction(ISD::SETCCE          , MVT::i32  , Custom);
427   if (Subtarget->is64Bit()) {
428     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
429     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
430     setOperationAction(ISD::SETCCE        , MVT::i64  , Custom);
431   }
432   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
433   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
434   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
435   // support continuation, user-level threading, and etc.. As a result, no
436   // other SjLj exception interfaces are implemented and please don't build
437   // your own exception handling based on them.
438   // LLVM/Clang supports zero-cost DWARF exception handling.
439   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
440   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
441
442   // Darwin ABI issue.
443   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
444   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
445   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
446   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
447   if (Subtarget->is64Bit())
448     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
449   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
450   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
453     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
454     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
455     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
456     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
457   }
458   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
459   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
460   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
461   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
462   if (Subtarget->is64Bit()) {
463     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
464     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
465     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
466   }
467
468   if (Subtarget->hasSSE1())
469     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
470
471   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
472
473   // Expand certain atomics
474   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
475     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
476     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
477     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
478   }
479
480   if (Subtarget->hasCmpxchg16b()) {
481     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
482   }
483
484   // FIXME - use subtarget debug flags
485   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
486       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
487     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
488   }
489
490   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
491   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492
493   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
494   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495
496   setOperationAction(ISD::TRAP, MVT::Other, Legal);
497   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498
499   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
500   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
501   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
502   if (Subtarget->is64Bit()) {
503     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
504     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
505   } else {
506     // TargetInfo::CharPtrBuiltinVaList
507     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
508     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
509   }
510
511   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
512   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
513
514   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
515
516   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
518   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519
520   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
521     // f32 and f64 use SSE.
522     // Set up the FP register classes.
523     addRegisterClass(MVT::f32, &X86::FR32RegClass);
524     addRegisterClass(MVT::f64, &X86::FR64RegClass);
525
526     // Use ANDPD to simulate FABS.
527     setOperationAction(ISD::FABS , MVT::f64, Custom);
528     setOperationAction(ISD::FABS , MVT::f32, Custom);
529
530     // Use XORP to simulate FNEG.
531     setOperationAction(ISD::FNEG , MVT::f64, Custom);
532     setOperationAction(ISD::FNEG , MVT::f32, Custom);
533
534     // Use ANDPD and ORPD to simulate FCOPYSIGN.
535     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
536     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537
538     // Lower this to FGETSIGNx86 plus an AND.
539     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
540     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541
542     // We don't support sin/cos/fmod
543     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
544     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
545     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
546     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
547     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
548     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549
550     // Expand FP immediates into loads from the stack, except for the special
551     // cases we handle.
552     addLegalFPImmediate(APFloat(+0.0)); // xorpd
553     addLegalFPImmediate(APFloat(+0.0f)); // xorps
554   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
555     // Use SSE for f32, x87 for f64.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, &X86::FR32RegClass);
558     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560     // Use ANDPS to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563     // Use XORP to simulate FNEG.
564     setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
567
568     // Use ANDPS and ORPS to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // We don't support sin/cos/fmod
573     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
575     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576
577     // Special cases we handle for FP constants.
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579     addLegalFPImmediate(APFloat(+0.0)); // FLD0
580     addLegalFPImmediate(APFloat(+1.0)); // FLD1
581     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
582     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583
584     if (!TM.Options.UnsafeFPMath) {
585       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
586       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
587       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588     }
589   } else if (!Subtarget->useSoftFloat()) {
590     // f32 and f64 in x87.
591     // Set up the FP register classes.
592     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
593     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
597     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599
600     if (!TM.Options.UnsafeFPMath) {
601       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
602       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
603       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
604       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
606       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607     }
608     addLegalFPImmediate(APFloat(+0.0)); // FLD0
609     addLegalFPImmediate(APFloat(+1.0)); // FLD1
610     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
613     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
614     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
615     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
616   }
617
618   // We don't support FMA.
619   setOperationAction(ISD::FMA, MVT::f64, Expand);
620   setOperationAction(ISD::FMA, MVT::f32, Expand);
621
622   // Long double always uses X87.
623   if (!Subtarget->useSoftFloat()) {
624     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
625     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
626     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627     {
628       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
629       addLegalFPImmediate(TmpFlt);  // FLD0
630       TmpFlt.changeSign();
631       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
632
633       bool ignored;
634       APFloat TmpFlt2(+1.0);
635       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636                       &ignored);
637       addLegalFPImmediate(TmpFlt2);  // FLD1
638       TmpFlt2.changeSign();
639       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
640     }
641
642     if (!TM.Options.UnsafeFPMath) {
643       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
644       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
645       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
646     }
647
648     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
649     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
650     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
651     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
652     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
653     setOperationAction(ISD::FMA, MVT::f80, Expand);
654   }
655
656   // Always use a library call for pow.
657   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
658   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
659   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
660
661   setOperationAction(ISD::FLOG, MVT::f80, Expand);
662   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
663   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
664   setOperationAction(ISD::FEXP, MVT::f80, Expand);
665   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
666   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
667   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668
669   // First set operation action for all vector types to either promote
670   // (for widening) or expand (for scalarization). Then we will selectively
671   // turn on ones that can be effectively codegen'd.
672   for (MVT VT : MVT::vector_valuetypes()) {
673     setOperationAction(ISD::ADD , VT, Expand);
674     setOperationAction(ISD::SUB , VT, Expand);
675     setOperationAction(ISD::FADD, VT, Expand);
676     setOperationAction(ISD::FNEG, VT, Expand);
677     setOperationAction(ISD::FSUB, VT, Expand);
678     setOperationAction(ISD::MUL , VT, Expand);
679     setOperationAction(ISD::FMUL, VT, Expand);
680     setOperationAction(ISD::SDIV, VT, Expand);
681     setOperationAction(ISD::UDIV, VT, Expand);
682     setOperationAction(ISD::FDIV, VT, Expand);
683     setOperationAction(ISD::SREM, VT, Expand);
684     setOperationAction(ISD::UREM, VT, Expand);
685     setOperationAction(ISD::LOAD, VT, Expand);
686     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
687     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
688     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
689     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
690     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
691     setOperationAction(ISD::FABS, VT, Expand);
692     setOperationAction(ISD::FSIN, VT, Expand);
693     setOperationAction(ISD::FSINCOS, VT, Expand);
694     setOperationAction(ISD::FCOS, VT, Expand);
695     setOperationAction(ISD::FSINCOS, VT, Expand);
696     setOperationAction(ISD::FREM, VT, Expand);
697     setOperationAction(ISD::FMA,  VT, Expand);
698     setOperationAction(ISD::FPOWI, VT, Expand);
699     setOperationAction(ISD::FSQRT, VT, Expand);
700     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
701     setOperationAction(ISD::FFLOOR, VT, Expand);
702     setOperationAction(ISD::FCEIL, VT, Expand);
703     setOperationAction(ISD::FTRUNC, VT, Expand);
704     setOperationAction(ISD::FRINT, VT, Expand);
705     setOperationAction(ISD::FNEARBYINT, VT, Expand);
706     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
707     setOperationAction(ISD::MULHS, VT, Expand);
708     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
709     setOperationAction(ISD::MULHU, VT, Expand);
710     setOperationAction(ISD::SDIVREM, VT, Expand);
711     setOperationAction(ISD::UDIVREM, VT, Expand);
712     setOperationAction(ISD::FPOW, VT, Expand);
713     setOperationAction(ISD::CTPOP, VT, Expand);
714     setOperationAction(ISD::CTTZ, VT, Expand);
715     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
716     setOperationAction(ISD::CTLZ, VT, Expand);
717     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
718     setOperationAction(ISD::SHL, VT, Expand);
719     setOperationAction(ISD::SRA, VT, Expand);
720     setOperationAction(ISD::SRL, VT, Expand);
721     setOperationAction(ISD::ROTL, VT, Expand);
722     setOperationAction(ISD::ROTR, VT, Expand);
723     setOperationAction(ISD::BSWAP, VT, Expand);
724     setOperationAction(ISD::SETCC, VT, Expand);
725     setOperationAction(ISD::FLOG, VT, Expand);
726     setOperationAction(ISD::FLOG2, VT, Expand);
727     setOperationAction(ISD::FLOG10, VT, Expand);
728     setOperationAction(ISD::FEXP, VT, Expand);
729     setOperationAction(ISD::FEXP2, VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
735     setOperationAction(ISD::TRUNCATE, VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
739     setOperationAction(ISD::VSELECT, VT, Expand);
740     setOperationAction(ISD::SELECT_CC, VT, Expand);
741     for (MVT InnerVT : MVT::vector_valuetypes()) {
742       setTruncStoreAction(InnerVT, VT, Expand);
743
744       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
745       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746
747       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
748       // types, we have to deal with them whether we ask for Expansion or not.
749       // Setting Expand causes its own optimisation problems though, so leave
750       // them legal.
751       if (VT.getVectorElementType() == MVT::i1)
752         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753
754       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
755       // split/scalarized right now.
756       if (VT.getVectorElementType() == MVT::f16)
757         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
758     }
759   }
760
761   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
762   // with -msoft-float, disable use of MMX as well.
763   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
764     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
765     // No operations on x86mmx supported, everything uses intrinsics.
766   }
767
768   // MMX-sized vectors (other than x86mmx) are expected to be expanded
769   // into smaller operations.
770   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
771     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
772     setOperationAction(ISD::AND,                MMXTy,      Expand);
773     setOperationAction(ISD::OR,                 MMXTy,      Expand);
774     setOperationAction(ISD::XOR,                MMXTy,      Expand);
775     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
776     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
777     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
778   }
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780
781   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
782     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783
784     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
785     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
786     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
787     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
788     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
789     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
790     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
791     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
793     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
794     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
796     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
797     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
798   }
799
800   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
801     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802
803     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
804     // registers cannot be used even for integer operations.
805     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
806     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
807     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
808     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809
810     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
811     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
812     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
813     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
814     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
815     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
818     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
819     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
820     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
833
834     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
835     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
836     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
837     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
838
839     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
840     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
841     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
842     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
843
844     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
845     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
848     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
849
850     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
851     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
852     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
853     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
854
855     setOperationAction(ISD::CTTZ,               MVT::v16i8, Custom);
856     setOperationAction(ISD::CTTZ,               MVT::v8i16, Custom);
857     setOperationAction(ISD::CTTZ,               MVT::v4i32, Custom);
858     // ISD::CTTZ v2i64 - scalarization is faster.
859     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v16i8, Custom);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v8i16, Custom);
861     setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::v4i32, Custom);
862     // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
863
864     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
865     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
866       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
867       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
868       setOperationAction(ISD::VSELECT,            VT, Custom);
869       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
870     }
871
872     // We support custom legalizing of sext and anyext loads for specific
873     // memory vector types which we can load as a scalar (or sequence of
874     // scalars) and extend in-register to a legal 128-bit vector type. For sext
875     // loads these must work with a single scalar load.
876     for (MVT VT : MVT::integer_vector_valuetypes()) {
877       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
878       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
879       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
880       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
881       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
882       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
883       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
884       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
885       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
886     }
887
888     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
890     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
892     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
893     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
894     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
895     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
896
897     if (Subtarget->is64Bit()) {
898       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
899       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
900     }
901
902     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
903     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
904       setOperationAction(ISD::AND,    VT, Promote);
905       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
906       setOperationAction(ISD::OR,     VT, Promote);
907       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
908       setOperationAction(ISD::XOR,    VT, Promote);
909       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
910       setOperationAction(ISD::LOAD,   VT, Promote);
911       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
912       setOperationAction(ISD::SELECT, VT, Promote);
913       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
914     }
915
916     // Custom lower v2i64 and v2f64 selects.
917     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
918     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
919     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
920     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
921
922     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
924
925     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
926
927     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
928     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
929     // As there is no 64-bit GPR available, we need build a special custom
930     // sequence to convert from v2i32 to v2f32.
931     if (!Subtarget->is64Bit())
932       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
933
934     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
935     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
936
937     for (MVT VT : MVT::fp_vector_valuetypes())
938       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
939
940     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
941     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
942     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
943   }
944
945   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
948       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
949       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
950       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
951       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
952     }
953
954     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
955     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
957     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
958     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
959     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
960     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
961     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
962
963     // FIXME: Do we need to handle scalar-to-vector here?
964     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
965
966     // We directly match byte blends in the backend as they match the VSELECT
967     // condition form.
968     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
969
970     // SSE41 brings specific instructions for doing vector sign extend even in
971     // cases where we don't have SRA.
972     for (MVT VT : MVT::integer_vector_valuetypes()) {
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
974       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
975       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
976     }
977
978     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
983     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
984     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
985
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
990     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
991     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
992
993     // i8 and i16 vectors are custom because the source register and source
994     // source memory operand types are not the same width.  f32 vectors are
995     // custom since the immediate controlling the insert encodes additional
996     // information.
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1001
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1004     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1005     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1006
1007     // FIXME: these should be Legal, but that's only for the case where
1008     // the index is constant.  For now custom expand to deal with that.
1009     if (Subtarget->is64Bit()) {
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1012     }
1013   }
1014
1015   if (Subtarget->hasSSE2()) {
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1017     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1019
1020     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1022
1023     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1024     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1025
1026     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1027     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1028
1029     // In the customized shift lowering, the legal cases in AVX2 will be
1030     // recognized.
1031     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1033
1034     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1035     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1036
1037     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1038     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1039   }
1040
1041   if (Subtarget->hasXOP()) {
1042     setOperationAction(ISD::ROTL,              MVT::v16i8, Custom);
1043     setOperationAction(ISD::ROTL,              MVT::v8i16, Custom);
1044     setOperationAction(ISD::ROTL,              MVT::v4i32, Custom);
1045     setOperationAction(ISD::ROTL,              MVT::v2i64, Custom);
1046     setOperationAction(ISD::ROTL,              MVT::v32i8, Custom);
1047     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1048     setOperationAction(ISD::ROTL,              MVT::v8i32, Custom);
1049     setOperationAction(ISD::ROTL,              MVT::v4i64, Custom);
1050   }
1051
1052   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1053     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1054     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1055     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1056     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1057     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1058     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1059
1060     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1061     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1063
1064     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1076
1077     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1078     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1079     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1082     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1083     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1084     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1085     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1086     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1087     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1088     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1089
1090     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1091     // even though v8i16 is a legal type.
1092     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1093     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1094     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1095
1096     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1097     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1098     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1099
1100     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1101     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1102
1103     for (MVT VT : MVT::fp_vector_valuetypes())
1104       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1105
1106     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1107     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1108
1109     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1110     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1111
1112     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1113     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1114
1115     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1116     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1117     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1118     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1119
1120     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1121     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1122     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1123
1124     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1125     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1126     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1127     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1128     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1129     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1130     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1131     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1132     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1133     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1134     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1135     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1136
1137     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1138     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1139     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1140     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1141
1142     setOperationAction(ISD::CTTZ,              MVT::v32i8, Custom);
1143     setOperationAction(ISD::CTTZ,              MVT::v16i16, Custom);
1144     setOperationAction(ISD::CTTZ,              MVT::v8i32, Custom);
1145     setOperationAction(ISD::CTTZ,              MVT::v4i64, Custom);
1146     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v32i8, Custom);
1147     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v16i16, Custom);
1148     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v8i32, Custom);
1149     setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::v4i64, Custom);
1150
1151     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1152       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1153       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1154       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1155       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1156       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1157       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1158     }
1159
1160     if (Subtarget->hasInt256()) {
1161       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1162       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1163       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1164       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1165
1166       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1167       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1168       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1169       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1170
1171       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1172       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1173       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1174       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1175
1176       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1177       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1178       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1179       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1180
1181       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1182       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1183       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1184       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1185       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1186       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1187       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1188       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1189       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1190       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1191       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1192       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1193
1194       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1195       // when we have a 256bit-wide blend with immediate.
1196       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1197
1198       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1199       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1200       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1201       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1202       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1203       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1204       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1205
1206       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1207       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1208       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1209       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1210       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1211       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1212     } else {
1213       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1214       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1215       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1216       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1217
1218       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1219       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1220       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1221       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1222
1223       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1224       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1225       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1227
1228       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1229       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1230       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1231       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1232       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1233       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1234       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1235       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1236       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1237       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1238       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1239       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1240     }
1241
1242     // In the customized shift lowering, the legal cases in AVX2 will be
1243     // recognized.
1244     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1245     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1246
1247     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1248     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1249
1250     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1251     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1252
1253     // Custom lower several nodes for 256-bit types.
1254     for (MVT VT : MVT::vector_valuetypes()) {
1255       if (VT.getScalarSizeInBits() >= 32) {
1256         setOperationAction(ISD::MLOAD,  VT, Legal);
1257         setOperationAction(ISD::MSTORE, VT, Legal);
1258       }
1259       // Extract subvector is special because the value type
1260       // (result) is 128-bit but the source is 256-bit wide.
1261       if (VT.is128BitVector()) {
1262         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1263       }
1264       // Do not attempt to custom lower other non-256-bit vectors
1265       if (!VT.is256BitVector())
1266         continue;
1267
1268       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1269       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1270       setOperationAction(ISD::VSELECT,            VT, Custom);
1271       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1272       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1273       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1274       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1275       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1276     }
1277
1278     if (Subtarget->hasInt256())
1279       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1280
1281     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1282     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1283       setOperationAction(ISD::AND,    VT, Promote);
1284       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1285       setOperationAction(ISD::OR,     VT, Promote);
1286       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1287       setOperationAction(ISD::XOR,    VT, Promote);
1288       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1289       setOperationAction(ISD::LOAD,   VT, Promote);
1290       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1291       setOperationAction(ISD::SELECT, VT, Promote);
1292       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1293     }
1294   }
1295
1296   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1297     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1298     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1299     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1300     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1301
1302     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1303     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1304     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1305
1306     for (MVT VT : MVT::fp_vector_valuetypes())
1307       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1308
1309     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1310     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1311     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1312     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1313     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1314     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1315     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1316     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1317     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1318     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1319     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1320     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1321
1322     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1323     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1324     setOperationAction(ISD::SELECT_CC,          MVT::i1,    Expand);
1325     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1326     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1327     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1328     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1329     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1330     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1331     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1333     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1334     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1335     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1336
1337     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1339     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1341     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1342     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1343
1344     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1345     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1348     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1349     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1350     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1351     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1352
1353     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1354     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1355     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1356     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1357     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1358     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1359     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1360     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1361     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1363     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1364     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1365     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1366     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1367     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1368     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1369
1370     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1371     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1372     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1373     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1374     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1375     if (Subtarget->hasVLX()){
1376       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1377       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1378       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1379       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1380       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1381
1382       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1383       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1384       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1385       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1386       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1387     }
1388     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1389     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1390     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1391     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i1,  Custom);
1392     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v16i1, Custom);
1393     if (Subtarget->hasDQI()) {
1394       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1395       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1396
1397       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1398       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1399       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1400       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1401       if (Subtarget->hasVLX()) {
1402         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1403         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1404         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1405         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1406         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1407         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1408         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1409         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1410       }
1411     }
1412     if (Subtarget->hasVLX()) {
1413       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1414       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1415       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1416       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1417       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1418       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1419       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1420       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1421     }
1422     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1423     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1424     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1425     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1426     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1427     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1428     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1429     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1430     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1431     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1434     if (Subtarget->hasDQI()) {
1435       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1436       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1437     }
1438     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1439     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1440     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1441     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1442     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1443     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1444     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1445     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1446     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1447     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1448
1449     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1450     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1451     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1452     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1453     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1,   Custom);
1454
1455     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1456     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1457
1458     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1459
1460     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1461     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1462     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1463     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1464     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1465     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1466     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1467     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1468     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1469     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1470     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1471
1472     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1473     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1474     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1475     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1476     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1477     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1478     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1479     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1480
1481     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1482     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1483
1484     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1485     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1486
1487     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1488
1489     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1490     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1491
1492     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1493     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1494
1495     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1496     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1497
1498     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1499     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1500     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1501     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1502     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1503     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1504
1505     if (Subtarget->hasCDI()) {
1506       setOperationAction(ISD::CTLZ,             MVT::v8i64,  Legal);
1507       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1508       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i64,  Legal);
1509       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i32, Legal);
1510
1511       setOperationAction(ISD::CTLZ,             MVT::v8i16,  Custom);
1512       setOperationAction(ISD::CTLZ,             MVT::v16i8,  Custom);
1513       setOperationAction(ISD::CTLZ,             MVT::v16i16, Custom);
1514       setOperationAction(ISD::CTLZ,             MVT::v32i8,  Custom);
1515       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i16,  Custom);
1516       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i8,  Custom);
1517       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v16i16, Custom);
1518       setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v32i8,  Custom);
1519
1520       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i64,  Custom);
1521       setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v16i32, Custom);
1522
1523       if (Subtarget->hasVLX()) {
1524         setOperationAction(ISD::CTLZ,             MVT::v4i64, Legal);
1525         setOperationAction(ISD::CTLZ,             MVT::v8i32, Legal);
1526         setOperationAction(ISD::CTLZ,             MVT::v2i64, Legal);
1527         setOperationAction(ISD::CTLZ,             MVT::v4i32, Legal);
1528         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Legal);
1529         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Legal);
1530         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Legal);
1531         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Legal);
1532
1533         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1534         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1535         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1536         setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1537       } else {
1538         setOperationAction(ISD::CTLZ,             MVT::v4i64, Custom);
1539         setOperationAction(ISD::CTLZ,             MVT::v8i32, Custom);
1540         setOperationAction(ISD::CTLZ,             MVT::v2i64, Custom);
1541         setOperationAction(ISD::CTLZ,             MVT::v4i32, Custom);
1542         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i64, Custom);
1543         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v8i32, Custom);
1544         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v2i64, Custom);
1545         setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::v4i32, Custom);
1546       }
1547     } // Subtarget->hasCDI()
1548
1549     if (Subtarget->hasDQI()) {
1550       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1551       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1552       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1553     }
1554     // Custom lower several nodes.
1555     for (MVT VT : MVT::vector_valuetypes()) {
1556       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1557       if (EltSize == 1) {
1558         setOperationAction(ISD::AND, VT, Legal);
1559         setOperationAction(ISD::OR,  VT, Legal);
1560         setOperationAction(ISD::XOR,  VT, Legal);
1561       }
1562       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1563         setOperationAction(ISD::MGATHER,  VT, Custom);
1564         setOperationAction(ISD::MSCATTER, VT, Custom);
1565       }
1566       // Extract subvector is special because the value type
1567       // (result) is 256/128-bit but the source is 512-bit wide.
1568       if (VT.is128BitVector() || VT.is256BitVector()) {
1569         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1570       }
1571       if (VT.getVectorElementType() == MVT::i1)
1572         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1573
1574       // Do not attempt to custom lower other non-512-bit vectors
1575       if (!VT.is512BitVector())
1576         continue;
1577
1578       if (EltSize >= 32) {
1579         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1580         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1581         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1582         setOperationAction(ISD::VSELECT,             VT, Legal);
1583         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1584         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1585         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1586         setOperationAction(ISD::MLOAD,               VT, Legal);
1587         setOperationAction(ISD::MSTORE,              VT, Legal);
1588       }
1589     }
1590     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1591       setOperationAction(ISD::SELECT, VT, Promote);
1592       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1593     }
1594   }// has  AVX-512
1595
1596   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1597     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1598     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1599
1600     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1601     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1602
1603     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1604     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1605     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1606     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1607     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1608     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1609     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1610     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1611     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1612     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1613     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1614     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1615     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1616     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i16, Custom);
1617     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i8, Custom);
1618     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1619     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1620     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i16, Custom);
1621     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i8, Custom);
1622     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1623     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1624     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1625     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1626     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1627     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1628     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1629     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1630     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i16, Custom);
1631     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i8, Custom);
1632     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1633     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1634     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1635     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1636     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i16, Custom);
1637     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i8, Custom);
1638     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1639     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1640     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1641     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1642     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1643     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v32i1, Custom);
1644     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v64i1, Custom);
1645
1646     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1647     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1648     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1649     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1650     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1651     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1652     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1653     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1654
1655     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1656     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1657     if (Subtarget->hasVLX())
1658       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1659
1660     if (Subtarget->hasCDI()) {
1661       setOperationAction(ISD::CTLZ,            MVT::v32i16, Custom);
1662       setOperationAction(ISD::CTLZ,            MVT::v64i8,  Custom);
1663       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1664       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8,  Custom);
1665     }
1666
1667     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1668       setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1669       setOperationAction(ISD::VSELECT,             VT, Legal);
1670     }
1671   }
1672
1673   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1674     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1675     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1676
1677     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1678     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1679     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1680     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1681     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1682     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1683     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1684     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1685     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1686     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1687     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i1, Custom);
1688     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i1, Custom);
1689
1690     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1691     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1692     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1693     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1694     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1695     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1696     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1697     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1698
1699     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1700     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1701     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1702     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1703     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1704     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1705     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1706     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1707   }
1708
1709   // We want to custom lower some of our intrinsics.
1710   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1711   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1712   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1713   if (!Subtarget->is64Bit())
1714     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1715
1716   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1717   // handle type legalization for these operations here.
1718   //
1719   // FIXME: We really should do custom legalization for addition and
1720   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1721   // than generic legalization for 64-bit multiplication-with-overflow, though.
1722   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1723     if (VT == MVT::i64 && !Subtarget->is64Bit())
1724       continue;
1725     // Add/Sub/Mul with overflow operations are custom lowered.
1726     setOperationAction(ISD::SADDO, VT, Custom);
1727     setOperationAction(ISD::UADDO, VT, Custom);
1728     setOperationAction(ISD::SSUBO, VT, Custom);
1729     setOperationAction(ISD::USUBO, VT, Custom);
1730     setOperationAction(ISD::SMULO, VT, Custom);
1731     setOperationAction(ISD::UMULO, VT, Custom);
1732   }
1733
1734   if (!Subtarget->is64Bit()) {
1735     // These libcalls are not available in 32-bit.
1736     setLibcallName(RTLIB::SHL_I128, nullptr);
1737     setLibcallName(RTLIB::SRL_I128, nullptr);
1738     setLibcallName(RTLIB::SRA_I128, nullptr);
1739   }
1740
1741   // Combine sin / cos into one node or libcall if possible.
1742   if (Subtarget->hasSinCos()) {
1743     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1744     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1745     if (Subtarget->isTargetDarwin()) {
1746       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1747       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1748       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1749       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1750     }
1751   }
1752
1753   if (Subtarget->isTargetWin64()) {
1754     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1755     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1756     setOperationAction(ISD::SREM, MVT::i128, Custom);
1757     setOperationAction(ISD::UREM, MVT::i128, Custom);
1758     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1759     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1760   }
1761
1762   // We have target-specific dag combine patterns for the following nodes:
1763   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1764   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1765   setTargetDAGCombine(ISD::BITCAST);
1766   setTargetDAGCombine(ISD::VSELECT);
1767   setTargetDAGCombine(ISD::SELECT);
1768   setTargetDAGCombine(ISD::SHL);
1769   setTargetDAGCombine(ISD::SRA);
1770   setTargetDAGCombine(ISD::SRL);
1771   setTargetDAGCombine(ISD::OR);
1772   setTargetDAGCombine(ISD::AND);
1773   setTargetDAGCombine(ISD::ADD);
1774   setTargetDAGCombine(ISD::FADD);
1775   setTargetDAGCombine(ISD::FSUB);
1776   setTargetDAGCombine(ISD::FNEG);
1777   setTargetDAGCombine(ISD::FMA);
1778   setTargetDAGCombine(ISD::SUB);
1779   setTargetDAGCombine(ISD::LOAD);
1780   setTargetDAGCombine(ISD::MLOAD);
1781   setTargetDAGCombine(ISD::STORE);
1782   setTargetDAGCombine(ISD::MSTORE);
1783   setTargetDAGCombine(ISD::TRUNCATE);
1784   setTargetDAGCombine(ISD::ZERO_EXTEND);
1785   setTargetDAGCombine(ISD::ANY_EXTEND);
1786   setTargetDAGCombine(ISD::SIGN_EXTEND);
1787   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1788   setTargetDAGCombine(ISD::SINT_TO_FP);
1789   setTargetDAGCombine(ISD::UINT_TO_FP);
1790   setTargetDAGCombine(ISD::SETCC);
1791   setTargetDAGCombine(ISD::BUILD_VECTOR);
1792   setTargetDAGCombine(ISD::MUL);
1793   setTargetDAGCombine(ISD::XOR);
1794
1795   computeRegisterProperties(Subtarget->getRegisterInfo());
1796
1797   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1798   MaxStoresPerMemsetOptSize = 8;
1799   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1800   MaxStoresPerMemcpyOptSize = 4;
1801   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1802   MaxStoresPerMemmoveOptSize = 4;
1803   setPrefLoopAlignment(4); // 2^4 bytes.
1804
1805   // A predictable cmov does not hurt on an in-order CPU.
1806   // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1807   PredictableSelectIsExpensive = !Subtarget->isAtom();
1808   EnableExtLdPromotion = true;
1809   setPrefFunctionAlignment(4); // 2^4 bytes.
1810
1811   verifyIntrinsicTables();
1812 }
1813
1814 // This has so far only been implemented for 64-bit MachO.
1815 bool X86TargetLowering::useLoadStackGuardNode() const {
1816   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1817 }
1818
1819 TargetLoweringBase::LegalizeTypeAction
1820 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1821   if (ExperimentalVectorWideningLegalization &&
1822       VT.getVectorNumElements() != 1 &&
1823       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1824     return TypeWidenVector;
1825
1826   return TargetLoweringBase::getPreferredVectorAction(VT);
1827 }
1828
1829 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1830                                           EVT VT) const {
1831   if (!VT.isVector())
1832     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1833
1834   if (VT.isSimple()) {
1835     MVT VVT = VT.getSimpleVT();
1836     const unsigned NumElts = VVT.getVectorNumElements();
1837     const MVT EltVT = VVT.getVectorElementType();
1838     if (VVT.is512BitVector()) {
1839       if (Subtarget->hasAVX512())
1840         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1841             EltVT == MVT::f32 || EltVT == MVT::f64)
1842           switch(NumElts) {
1843           case  8: return MVT::v8i1;
1844           case 16: return MVT::v16i1;
1845         }
1846       if (Subtarget->hasBWI())
1847         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1848           switch(NumElts) {
1849           case 32: return MVT::v32i1;
1850           case 64: return MVT::v64i1;
1851         }
1852     }
1853
1854     if (VVT.is256BitVector() || VVT.is128BitVector()) {
1855       if (Subtarget->hasVLX())
1856         if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1857             EltVT == MVT::f32 || EltVT == MVT::f64)
1858           switch(NumElts) {
1859           case 2: return MVT::v2i1;
1860           case 4: return MVT::v4i1;
1861           case 8: return MVT::v8i1;
1862         }
1863       if (Subtarget->hasBWI() && Subtarget->hasVLX())
1864         if (EltVT == MVT::i8 || EltVT == MVT::i16)
1865           switch(NumElts) {
1866           case  8: return MVT::v8i1;
1867           case 16: return MVT::v16i1;
1868           case 32: return MVT::v32i1;
1869         }
1870     }
1871   }
1872
1873   return VT.changeVectorElementTypeToInteger();
1874 }
1875
1876 /// Helper for getByValTypeAlignment to determine
1877 /// the desired ByVal argument alignment.
1878 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1879   if (MaxAlign == 16)
1880     return;
1881   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1882     if (VTy->getBitWidth() == 128)
1883       MaxAlign = 16;
1884   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1885     unsigned EltAlign = 0;
1886     getMaxByValAlign(ATy->getElementType(), EltAlign);
1887     if (EltAlign > MaxAlign)
1888       MaxAlign = EltAlign;
1889   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1890     for (auto *EltTy : STy->elements()) {
1891       unsigned EltAlign = 0;
1892       getMaxByValAlign(EltTy, EltAlign);
1893       if (EltAlign > MaxAlign)
1894         MaxAlign = EltAlign;
1895       if (MaxAlign == 16)
1896         break;
1897     }
1898   }
1899 }
1900
1901 /// Return the desired alignment for ByVal aggregate
1902 /// function arguments in the caller parameter area. For X86, aggregates
1903 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1904 /// are at 4-byte boundaries.
1905 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1906                                                   const DataLayout &DL) const {
1907   if (Subtarget->is64Bit()) {
1908     // Max of 8 and alignment of type.
1909     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1910     if (TyAlign > 8)
1911       return TyAlign;
1912     return 8;
1913   }
1914
1915   unsigned Align = 4;
1916   if (Subtarget->hasSSE1())
1917     getMaxByValAlign(Ty, Align);
1918   return Align;
1919 }
1920
1921 /// Returns the target specific optimal type for load
1922 /// and store operations as a result of memset, memcpy, and memmove
1923 /// lowering. If DstAlign is zero that means it's safe to destination
1924 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1925 /// means there isn't a need to check it against alignment requirement,
1926 /// probably because the source does not need to be loaded. If 'IsMemset' is
1927 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1928 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1929 /// source is constant so it does not need to be loaded.
1930 /// It returns EVT::Other if the type should be determined using generic
1931 /// target-independent logic.
1932 EVT
1933 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1934                                        unsigned DstAlign, unsigned SrcAlign,
1935                                        bool IsMemset, bool ZeroMemset,
1936                                        bool MemcpyStrSrc,
1937                                        MachineFunction &MF) const {
1938   const Function *F = MF.getFunction();
1939   if ((!IsMemset || ZeroMemset) &&
1940       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1941     if (Size >= 16 &&
1942         (!Subtarget->isUnalignedMem16Slow() ||
1943          ((DstAlign == 0 || DstAlign >= 16) &&
1944           (SrcAlign == 0 || SrcAlign >= 16)))) {
1945       if (Size >= 32) {
1946         // FIXME: Check if unaligned 32-byte accesses are slow.
1947         if (Subtarget->hasInt256())
1948           return MVT::v8i32;
1949         if (Subtarget->hasFp256())
1950           return MVT::v8f32;
1951       }
1952       if (Subtarget->hasSSE2())
1953         return MVT::v4i32;
1954       if (Subtarget->hasSSE1())
1955         return MVT::v4f32;
1956     } else if (!MemcpyStrSrc && Size >= 8 &&
1957                !Subtarget->is64Bit() &&
1958                Subtarget->hasSSE2()) {
1959       // Do not use f64 to lower memcpy if source is string constant. It's
1960       // better to use i32 to avoid the loads.
1961       return MVT::f64;
1962     }
1963   }
1964   // This is a compromise. If we reach here, unaligned accesses may be slow on
1965   // this target. However, creating smaller, aligned accesses could be even
1966   // slower and would certainly be a lot more code.
1967   if (Subtarget->is64Bit() && Size >= 8)
1968     return MVT::i64;
1969   return MVT::i32;
1970 }
1971
1972 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1973   if (VT == MVT::f32)
1974     return X86ScalarSSEf32;
1975   else if (VT == MVT::f64)
1976     return X86ScalarSSEf64;
1977   return true;
1978 }
1979
1980 bool
1981 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1982                                                   unsigned,
1983                                                   unsigned,
1984                                                   bool *Fast) const {
1985   if (Fast) {
1986     switch (VT.getSizeInBits()) {
1987     default:
1988       // 8-byte and under are always assumed to be fast.
1989       *Fast = true;
1990       break;
1991     case 128:
1992       *Fast = !Subtarget->isUnalignedMem16Slow();
1993       break;
1994     case 256:
1995       *Fast = !Subtarget->isUnalignedMem32Slow();
1996       break;
1997     // TODO: What about AVX-512 (512-bit) accesses?
1998     }
1999   }
2000   // Misaligned accesses of any size are always allowed.
2001   return true;
2002 }
2003
2004 /// Return the entry encoding for a jump table in the
2005 /// current function.  The returned value is a member of the
2006 /// MachineJumpTableInfo::JTEntryKind enum.
2007 unsigned X86TargetLowering::getJumpTableEncoding() const {
2008   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2009   // symbol.
2010   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2011       Subtarget->isPICStyleGOT())
2012     return MachineJumpTableInfo::EK_Custom32;
2013
2014   // Otherwise, use the normal jump table encoding heuristics.
2015   return TargetLowering::getJumpTableEncoding();
2016 }
2017
2018 bool X86TargetLowering::useSoftFloat() const {
2019   return Subtarget->useSoftFloat();
2020 }
2021
2022 const MCExpr *
2023 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2024                                              const MachineBasicBlock *MBB,
2025                                              unsigned uid,MCContext &Ctx) const{
2026   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2027          Subtarget->isPICStyleGOT());
2028   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2029   // entries.
2030   return MCSymbolRefExpr::create(MBB->getSymbol(),
2031                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2032 }
2033
2034 /// Returns relocation base for the given PIC jumptable.
2035 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2036                                                     SelectionDAG &DAG) const {
2037   if (!Subtarget->is64Bit())
2038     // This doesn't have SDLoc associated with it, but is not really the
2039     // same as a Register.
2040     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2041                        getPointerTy(DAG.getDataLayout()));
2042   return Table;
2043 }
2044
2045 /// This returns the relocation base for the given PIC jumptable,
2046 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2047 const MCExpr *X86TargetLowering::
2048 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2049                              MCContext &Ctx) const {
2050   // X86-64 uses RIP relative addressing based on the jump table label.
2051   if (Subtarget->isPICStyleRIPRel())
2052     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2053
2054   // Otherwise, the reference is relative to the PIC base.
2055   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2056 }
2057
2058 std::pair<const TargetRegisterClass *, uint8_t>
2059 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2060                                            MVT VT) const {
2061   const TargetRegisterClass *RRC = nullptr;
2062   uint8_t Cost = 1;
2063   switch (VT.SimpleTy) {
2064   default:
2065     return TargetLowering::findRepresentativeClass(TRI, VT);
2066   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2067     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2068     break;
2069   case MVT::x86mmx:
2070     RRC = &X86::VR64RegClass;
2071     break;
2072   case MVT::f32: case MVT::f64:
2073   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2074   case MVT::v4f32: case MVT::v2f64:
2075   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2076   case MVT::v4f64:
2077     RRC = &X86::VR128RegClass;
2078     break;
2079   }
2080   return std::make_pair(RRC, Cost);
2081 }
2082
2083 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2084                                                unsigned &Offset) const {
2085   if (!Subtarget->isTargetLinux())
2086     return false;
2087
2088   if (Subtarget->is64Bit()) {
2089     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2090     Offset = 0x28;
2091     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2092       AddressSpace = 256;
2093     else
2094       AddressSpace = 257;
2095   } else {
2096     // %gs:0x14 on i386
2097     Offset = 0x14;
2098     AddressSpace = 256;
2099   }
2100   return true;
2101 }
2102
2103 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2104   if (!Subtarget->isTargetAndroid())
2105     return TargetLowering::getSafeStackPointerLocation(IRB);
2106
2107   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2108   // definition of TLS_SLOT_SAFESTACK in
2109   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2110   unsigned AddressSpace, Offset;
2111   if (Subtarget->is64Bit()) {
2112     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2113     Offset = 0x48;
2114     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2115       AddressSpace = 256;
2116     else
2117       AddressSpace = 257;
2118   } else {
2119     // %gs:0x24 on i386
2120     Offset = 0x24;
2121     AddressSpace = 256;
2122   }
2123
2124   return ConstantExpr::getIntToPtr(
2125       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2126       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2127 }
2128
2129 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2130                                             unsigned DestAS) const {
2131   assert(SrcAS != DestAS && "Expected different address spaces!");
2132
2133   return SrcAS < 256 && DestAS < 256;
2134 }
2135
2136 //===----------------------------------------------------------------------===//
2137 //               Return Value Calling Convention Implementation
2138 //===----------------------------------------------------------------------===//
2139
2140 #include "X86GenCallingConv.inc"
2141
2142 bool X86TargetLowering::CanLowerReturn(
2143     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2144     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2145   SmallVector<CCValAssign, 16> RVLocs;
2146   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2147   return CCInfo.CheckReturn(Outs, RetCC_X86);
2148 }
2149
2150 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2151   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2152   return ScratchRegs;
2153 }
2154
2155 SDValue
2156 X86TargetLowering::LowerReturn(SDValue Chain,
2157                                CallingConv::ID CallConv, bool isVarArg,
2158                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2159                                const SmallVectorImpl<SDValue> &OutVals,
2160                                SDLoc dl, SelectionDAG &DAG) const {
2161   MachineFunction &MF = DAG.getMachineFunction();
2162   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2163
2164   SmallVector<CCValAssign, 16> RVLocs;
2165   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2166   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2167
2168   SDValue Flag;
2169   SmallVector<SDValue, 6> RetOps;
2170   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2171   // Operand #1 = Bytes To Pop
2172   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2173                    MVT::i16));
2174
2175   // Copy the result values into the output registers.
2176   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2177     CCValAssign &VA = RVLocs[i];
2178     assert(VA.isRegLoc() && "Can only return in registers!");
2179     SDValue ValToCopy = OutVals[i];
2180     EVT ValVT = ValToCopy.getValueType();
2181
2182     // Promote values to the appropriate types.
2183     if (VA.getLocInfo() == CCValAssign::SExt)
2184       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2185     else if (VA.getLocInfo() == CCValAssign::ZExt)
2186       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2187     else if (VA.getLocInfo() == CCValAssign::AExt) {
2188       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2189         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2190       else
2191         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2192     }
2193     else if (VA.getLocInfo() == CCValAssign::BCvt)
2194       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2195
2196     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2197            "Unexpected FP-extend for return value.");
2198
2199     // If this is x86-64, and we disabled SSE, we can't return FP values,
2200     // or SSE or MMX vectors.
2201     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2202          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2203           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2204       report_fatal_error("SSE register return with SSE disabled");
2205     }
2206     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2207     // llvm-gcc has never done it right and no one has noticed, so this
2208     // should be OK for now.
2209     if (ValVT == MVT::f64 &&
2210         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2211       report_fatal_error("SSE2 register return with SSE2 disabled");
2212
2213     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2214     // the RET instruction and handled by the FP Stackifier.
2215     if (VA.getLocReg() == X86::FP0 ||
2216         VA.getLocReg() == X86::FP1) {
2217       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2218       // change the value to the FP stack register class.
2219       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2220         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2221       RetOps.push_back(ValToCopy);
2222       // Don't emit a copytoreg.
2223       continue;
2224     }
2225
2226     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2227     // which is returned in RAX / RDX.
2228     if (Subtarget->is64Bit()) {
2229       if (ValVT == MVT::x86mmx) {
2230         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2231           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2232           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2233                                   ValToCopy);
2234           // If we don't have SSE2 available, convert to v4f32 so the generated
2235           // register is legal.
2236           if (!Subtarget->hasSSE2())
2237             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2238         }
2239       }
2240     }
2241
2242     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2243     Flag = Chain.getValue(1);
2244     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2245   }
2246
2247   // All x86 ABIs require that for returning structs by value we copy
2248   // the sret argument into %rax/%eax (depending on ABI) for the return.
2249   // We saved the argument into a virtual register in the entry block,
2250   // so now we copy the value out and into %rax/%eax.
2251   //
2252   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2253   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2254   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2255   // either case FuncInfo->setSRetReturnReg() will have been called.
2256   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2257     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2258                                      getPointerTy(MF.getDataLayout()));
2259
2260     unsigned RetValReg
2261         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2262           X86::RAX : X86::EAX;
2263     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2264     Flag = Chain.getValue(1);
2265
2266     // RAX/EAX now acts like a return value.
2267     RetOps.push_back(
2268         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2269   }
2270
2271   RetOps[0] = Chain;  // Update chain.
2272
2273   // Add the flag if we have it.
2274   if (Flag.getNode())
2275     RetOps.push_back(Flag);
2276
2277   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2278 }
2279
2280 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2281   if (N->getNumValues() != 1)
2282     return false;
2283   if (!N->hasNUsesOfValue(1, 0))
2284     return false;
2285
2286   SDValue TCChain = Chain;
2287   SDNode *Copy = *N->use_begin();
2288   if (Copy->getOpcode() == ISD::CopyToReg) {
2289     // If the copy has a glue operand, we conservatively assume it isn't safe to
2290     // perform a tail call.
2291     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2292       return false;
2293     TCChain = Copy->getOperand(0);
2294   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2295     return false;
2296
2297   bool HasRet = false;
2298   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2299        UI != UE; ++UI) {
2300     if (UI->getOpcode() != X86ISD::RET_FLAG)
2301       return false;
2302     // If we are returning more than one value, we can definitely
2303     // not make a tail call see PR19530
2304     if (UI->getNumOperands() > 4)
2305       return false;
2306     if (UI->getNumOperands() == 4 &&
2307         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2308       return false;
2309     HasRet = true;
2310   }
2311
2312   if (!HasRet)
2313     return false;
2314
2315   Chain = TCChain;
2316   return true;
2317 }
2318
2319 EVT
2320 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2321                                             ISD::NodeType ExtendKind) const {
2322   MVT ReturnMVT;
2323   // TODO: Is this also valid on 32-bit?
2324   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2325     ReturnMVT = MVT::i8;
2326   else
2327     ReturnMVT = MVT::i32;
2328
2329   EVT MinVT = getRegisterType(Context, ReturnMVT);
2330   return VT.bitsLT(MinVT) ? MinVT : VT;
2331 }
2332
2333 /// Lower the result values of a call into the
2334 /// appropriate copies out of appropriate physical registers.
2335 ///
2336 SDValue
2337 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2338                                    CallingConv::ID CallConv, bool isVarArg,
2339                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2340                                    SDLoc dl, SelectionDAG &DAG,
2341                                    SmallVectorImpl<SDValue> &InVals) const {
2342
2343   // Assign locations to each value returned by this call.
2344   SmallVector<CCValAssign, 16> RVLocs;
2345   bool Is64Bit = Subtarget->is64Bit();
2346   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2347                  *DAG.getContext());
2348   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2349
2350   // Copy all of the result registers out of their specified physreg.
2351   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2352     CCValAssign &VA = RVLocs[i];
2353     EVT CopyVT = VA.getLocVT();
2354
2355     // If this is x86-64, and we disabled SSE, we can't return FP values
2356     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2357         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2358       report_fatal_error("SSE register return with SSE disabled");
2359     }
2360
2361     // If we prefer to use the value in xmm registers, copy it out as f80 and
2362     // use a truncate to move it from fp stack reg to xmm reg.
2363     bool RoundAfterCopy = false;
2364     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2365         isScalarFPTypeInSSEReg(VA.getValVT())) {
2366       CopyVT = MVT::f80;
2367       RoundAfterCopy = (CopyVT != VA.getLocVT());
2368     }
2369
2370     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2371                                CopyVT, InFlag).getValue(1);
2372     SDValue Val = Chain.getValue(0);
2373
2374     if (RoundAfterCopy)
2375       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2376                         // This truncation won't change the value.
2377                         DAG.getIntPtrConstant(1, dl));
2378
2379     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2380       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2381
2382     InFlag = Chain.getValue(2);
2383     InVals.push_back(Val);
2384   }
2385
2386   return Chain;
2387 }
2388
2389 //===----------------------------------------------------------------------===//
2390 //                C & StdCall & Fast Calling Convention implementation
2391 //===----------------------------------------------------------------------===//
2392 //  StdCall calling convention seems to be standard for many Windows' API
2393 //  routines and around. It differs from C calling convention just a little:
2394 //  callee should clean up the stack, not caller. Symbols should be also
2395 //  decorated in some fancy way :) It doesn't support any vector arguments.
2396 //  For info on fast calling convention see Fast Calling Convention (tail call)
2397 //  implementation LowerX86_32FastCCCallTo.
2398
2399 /// CallIsStructReturn - Determines whether a call uses struct return
2400 /// semantics.
2401 enum StructReturnType {
2402   NotStructReturn,
2403   RegStructReturn,
2404   StackStructReturn
2405 };
2406 static StructReturnType
2407 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2408   if (Outs.empty())
2409     return NotStructReturn;
2410
2411   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2412   if (!Flags.isSRet())
2413     return NotStructReturn;
2414   if (Flags.isInReg())
2415     return RegStructReturn;
2416   return StackStructReturn;
2417 }
2418
2419 /// Determines whether a function uses struct return semantics.
2420 static StructReturnType
2421 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2422   if (Ins.empty())
2423     return NotStructReturn;
2424
2425   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2426   if (!Flags.isSRet())
2427     return NotStructReturn;
2428   if (Flags.isInReg())
2429     return RegStructReturn;
2430   return StackStructReturn;
2431 }
2432
2433 /// Make a copy of an aggregate at address specified by "Src" to address
2434 /// "Dst" with size and alignment information specified by the specific
2435 /// parameter attribute. The copy will be passed as a byval function parameter.
2436 static SDValue
2437 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2438                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2439                           SDLoc dl) {
2440   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2441
2442   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2443                        /*isVolatile*/false, /*AlwaysInline=*/true,
2444                        /*isTailCall*/false,
2445                        MachinePointerInfo(), MachinePointerInfo());
2446 }
2447
2448 /// Return true if the calling convention is one that we can guarantee TCO for.
2449 static bool canGuaranteeTCO(CallingConv::ID CC) {
2450   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2451           CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2452 }
2453
2454 /// Return true if we might ever do TCO for calls with this calling convention.
2455 static bool mayTailCallThisCC(CallingConv::ID CC) {
2456   switch (CC) {
2457   // C calling conventions:
2458   case CallingConv::C:
2459   case CallingConv::X86_64_Win64:
2460   case CallingConv::X86_64_SysV:
2461   // Callee pop conventions:
2462   case CallingConv::X86_ThisCall:
2463   case CallingConv::X86_StdCall:
2464   case CallingConv::X86_VectorCall:
2465   case CallingConv::X86_FastCall:
2466     return true;
2467   default:
2468     return canGuaranteeTCO(CC);
2469   }
2470 }
2471
2472 /// Return true if the function is being made into a tailcall target by
2473 /// changing its ABI.
2474 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2475   return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2476 }
2477
2478 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2479   auto Attr =
2480       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2481   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2482     return false;
2483
2484   CallSite CS(CI);
2485   CallingConv::ID CalleeCC = CS.getCallingConv();
2486   if (!mayTailCallThisCC(CalleeCC))
2487     return false;
2488
2489   return true;
2490 }
2491
2492 SDValue
2493 X86TargetLowering::LowerMemArgument(SDValue Chain,
2494                                     CallingConv::ID CallConv,
2495                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2496                                     SDLoc dl, SelectionDAG &DAG,
2497                                     const CCValAssign &VA,
2498                                     MachineFrameInfo *MFI,
2499                                     unsigned i) const {
2500   // Create the nodes corresponding to a load from this parameter slot.
2501   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2502   bool AlwaysUseMutable = shouldGuaranteeTCO(
2503       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2504   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2505   EVT ValVT;
2506
2507   // If value is passed by pointer we have address passed instead of the value
2508   // itself.
2509   bool ExtendedInMem = VA.isExtInLoc() &&
2510     VA.getValVT().getScalarType() == MVT::i1;
2511
2512   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2513     ValVT = VA.getLocVT();
2514   else
2515     ValVT = VA.getValVT();
2516
2517   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2518   // changed with more analysis.
2519   // In case of tail call optimization mark all arguments mutable. Since they
2520   // could be overwritten by lowering of arguments in case of a tail call.
2521   if (Flags.isByVal()) {
2522     unsigned Bytes = Flags.getByValSize();
2523     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2524     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2525     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2526   } else {
2527     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2528                                     VA.getLocMemOffset(), isImmutable);
2529     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2530     SDValue Val = DAG.getLoad(
2531         ValVT, dl, Chain, FIN,
2532         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2533         false, false, 0);
2534     return ExtendedInMem ?
2535       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2536   }
2537 }
2538
2539 // FIXME: Get this from tablegen.
2540 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2541                                                 const X86Subtarget *Subtarget) {
2542   assert(Subtarget->is64Bit());
2543
2544   if (Subtarget->isCallingConvWin64(CallConv)) {
2545     static const MCPhysReg GPR64ArgRegsWin64[] = {
2546       X86::RCX, X86::RDX, X86::R8,  X86::R9
2547     };
2548     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2549   }
2550
2551   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2552     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2553   };
2554   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2555 }
2556
2557 // FIXME: Get this from tablegen.
2558 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2559                                                 CallingConv::ID CallConv,
2560                                                 const X86Subtarget *Subtarget) {
2561   assert(Subtarget->is64Bit());
2562   if (Subtarget->isCallingConvWin64(CallConv)) {
2563     // The XMM registers which might contain var arg parameters are shadowed
2564     // in their paired GPR.  So we only need to save the GPR to their home
2565     // slots.
2566     // TODO: __vectorcall will change this.
2567     return None;
2568   }
2569
2570   const Function *Fn = MF.getFunction();
2571   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2572   bool isSoftFloat = Subtarget->useSoftFloat();
2573   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2574          "SSE register cannot be used when SSE is disabled!");
2575   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2576     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2577     // registers.
2578     return None;
2579
2580   static const MCPhysReg XMMArgRegs64Bit[] = {
2581     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2582     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2583   };
2584   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2585 }
2586
2587 SDValue X86TargetLowering::LowerFormalArguments(
2588     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2589     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2590     SmallVectorImpl<SDValue> &InVals) const {
2591   MachineFunction &MF = DAG.getMachineFunction();
2592   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2593   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2594
2595   const Function* Fn = MF.getFunction();
2596   if (Fn->hasExternalLinkage() &&
2597       Subtarget->isTargetCygMing() &&
2598       Fn->getName() == "main")
2599     FuncInfo->setForceFramePointer(true);
2600
2601   MachineFrameInfo *MFI = MF.getFrameInfo();
2602   bool Is64Bit = Subtarget->is64Bit();
2603   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2604
2605   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2606          "Var args not supported with calling convention fastcc, ghc or hipe");
2607
2608   // Assign locations to all of the incoming arguments.
2609   SmallVector<CCValAssign, 16> ArgLocs;
2610   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2611
2612   // Allocate shadow area for Win64
2613   if (IsWin64)
2614     CCInfo.AllocateStack(32, 8);
2615
2616   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2617
2618   unsigned LastVal = ~0U;
2619   SDValue ArgValue;
2620   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2621     CCValAssign &VA = ArgLocs[i];
2622     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2623     // places.
2624     assert(VA.getValNo() != LastVal &&
2625            "Don't support value assigned to multiple locs yet");
2626     (void)LastVal;
2627     LastVal = VA.getValNo();
2628
2629     if (VA.isRegLoc()) {
2630       EVT RegVT = VA.getLocVT();
2631       const TargetRegisterClass *RC;
2632       if (RegVT == MVT::i32)
2633         RC = &X86::GR32RegClass;
2634       else if (Is64Bit && RegVT == MVT::i64)
2635         RC = &X86::GR64RegClass;
2636       else if (RegVT == MVT::f32)
2637         RC = &X86::FR32RegClass;
2638       else if (RegVT == MVT::f64)
2639         RC = &X86::FR64RegClass;
2640       else if (RegVT.is512BitVector())
2641         RC = &X86::VR512RegClass;
2642       else if (RegVT.is256BitVector())
2643         RC = &X86::VR256RegClass;
2644       else if (RegVT.is128BitVector())
2645         RC = &X86::VR128RegClass;
2646       else if (RegVT == MVT::x86mmx)
2647         RC = &X86::VR64RegClass;
2648       else if (RegVT == MVT::i1)
2649         RC = &X86::VK1RegClass;
2650       else if (RegVT == MVT::v8i1)
2651         RC = &X86::VK8RegClass;
2652       else if (RegVT == MVT::v16i1)
2653         RC = &X86::VK16RegClass;
2654       else if (RegVT == MVT::v32i1)
2655         RC = &X86::VK32RegClass;
2656       else if (RegVT == MVT::v64i1)
2657         RC = &X86::VK64RegClass;
2658       else
2659         llvm_unreachable("Unknown argument type!");
2660
2661       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2662       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2663
2664       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2665       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2666       // right size.
2667       if (VA.getLocInfo() == CCValAssign::SExt)
2668         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2669                                DAG.getValueType(VA.getValVT()));
2670       else if (VA.getLocInfo() == CCValAssign::ZExt)
2671         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2672                                DAG.getValueType(VA.getValVT()));
2673       else if (VA.getLocInfo() == CCValAssign::BCvt)
2674         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2675
2676       if (VA.isExtInLoc()) {
2677         // Handle MMX values passed in XMM regs.
2678         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2679           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2680         else
2681           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2682       }
2683     } else {
2684       assert(VA.isMemLoc());
2685       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2686     }
2687
2688     // If value is passed via pointer - do a load.
2689     if (VA.getLocInfo() == CCValAssign::Indirect)
2690       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2691                              MachinePointerInfo(), false, false, false, 0);
2692
2693     InVals.push_back(ArgValue);
2694   }
2695
2696   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2697     // All x86 ABIs require that for returning structs by value we copy the
2698     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2699     // the argument into a virtual register so that we can access it from the
2700     // return points.
2701     if (Ins[i].Flags.isSRet()) {
2702       unsigned Reg = FuncInfo->getSRetReturnReg();
2703       if (!Reg) {
2704         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2705         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2706         FuncInfo->setSRetReturnReg(Reg);
2707       }
2708       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2709       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2710       break;
2711     }
2712   }
2713
2714   unsigned StackSize = CCInfo.getNextStackOffset();
2715   // Align stack specially for tail calls.
2716   if (shouldGuaranteeTCO(CallConv,
2717                          MF.getTarget().Options.GuaranteedTailCallOpt))
2718     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2719
2720   // If the function takes variable number of arguments, make a frame index for
2721   // the start of the first vararg value... for expansion of llvm.va_start. We
2722   // can skip this if there are no va_start calls.
2723   if (MFI->hasVAStart() &&
2724       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2725                    CallConv != CallingConv::X86_ThisCall))) {
2726     FuncInfo->setVarArgsFrameIndex(
2727         MFI->CreateFixedObject(1, StackSize, true));
2728   }
2729
2730   // Figure out if XMM registers are in use.
2731   assert(!(Subtarget->useSoftFloat() &&
2732            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2733          "SSE register cannot be used when SSE is disabled!");
2734
2735   // 64-bit calling conventions support varargs and register parameters, so we
2736   // have to do extra work to spill them in the prologue.
2737   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2738     // Find the first unallocated argument registers.
2739     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2740     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2741     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2742     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2743     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2744            "SSE register cannot be used when SSE is disabled!");
2745
2746     // Gather all the live in physical registers.
2747     SmallVector<SDValue, 6> LiveGPRs;
2748     SmallVector<SDValue, 8> LiveXMMRegs;
2749     SDValue ALVal;
2750     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2751       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2752       LiveGPRs.push_back(
2753           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2754     }
2755     if (!ArgXMMs.empty()) {
2756       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2757       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2758       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2759         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2760         LiveXMMRegs.push_back(
2761             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2762       }
2763     }
2764
2765     if (IsWin64) {
2766       // Get to the caller-allocated home save location.  Add 8 to account
2767       // for the return address.
2768       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2769       FuncInfo->setRegSaveFrameIndex(
2770           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2771       // Fixup to set vararg frame on shadow area (4 x i64).
2772       if (NumIntRegs < 4)
2773         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2774     } else {
2775       // For X86-64, if there are vararg parameters that are passed via
2776       // registers, then we must store them to their spots on the stack so
2777       // they may be loaded by deferencing the result of va_next.
2778       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2779       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2780       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2781           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2782     }
2783
2784     // Store the integer parameter registers.
2785     SmallVector<SDValue, 8> MemOps;
2786     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2787                                       getPointerTy(DAG.getDataLayout()));
2788     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2789     for (SDValue Val : LiveGPRs) {
2790       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2791                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2792       SDValue Store =
2793           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2794                        MachinePointerInfo::getFixedStack(
2795                            DAG.getMachineFunction(),
2796                            FuncInfo->getRegSaveFrameIndex(), Offset),
2797                        false, false, 0);
2798       MemOps.push_back(Store);
2799       Offset += 8;
2800     }
2801
2802     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2803       // Now store the XMM (fp + vector) parameter registers.
2804       SmallVector<SDValue, 12> SaveXMMOps;
2805       SaveXMMOps.push_back(Chain);
2806       SaveXMMOps.push_back(ALVal);
2807       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2808                              FuncInfo->getRegSaveFrameIndex(), dl));
2809       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2810                              FuncInfo->getVarArgsFPOffset(), dl));
2811       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2812                         LiveXMMRegs.end());
2813       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2814                                    MVT::Other, SaveXMMOps));
2815     }
2816
2817     if (!MemOps.empty())
2818       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2819   }
2820
2821   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2822     // Find the largest legal vector type.
2823     MVT VecVT = MVT::Other;
2824     // FIXME: Only some x86_32 calling conventions support AVX512.
2825     if (Subtarget->hasAVX512() &&
2826         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2827                      CallConv == CallingConv::Intel_OCL_BI)))
2828       VecVT = MVT::v16f32;
2829     else if (Subtarget->hasAVX())
2830       VecVT = MVT::v8f32;
2831     else if (Subtarget->hasSSE2())
2832       VecVT = MVT::v4f32;
2833
2834     // We forward some GPRs and some vector types.
2835     SmallVector<MVT, 2> RegParmTypes;
2836     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2837     RegParmTypes.push_back(IntVT);
2838     if (VecVT != MVT::Other)
2839       RegParmTypes.push_back(VecVT);
2840
2841     // Compute the set of forwarded registers. The rest are scratch.
2842     SmallVectorImpl<ForwardedRegister> &Forwards =
2843         FuncInfo->getForwardedMustTailRegParms();
2844     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2845
2846     // Conservatively forward AL on x86_64, since it might be used for varargs.
2847     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2848       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2849       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2850     }
2851
2852     // Copy all forwards from physical to virtual registers.
2853     for (ForwardedRegister &F : Forwards) {
2854       // FIXME: Can we use a less constrained schedule?
2855       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2856       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2857       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2858     }
2859   }
2860
2861   // Some CCs need callee pop.
2862   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2863                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2864     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2865   } else {
2866     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2867     // If this is an sret function, the return should pop the hidden pointer.
2868     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2869         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2870         argsAreStructReturn(Ins) == StackStructReturn)
2871       FuncInfo->setBytesToPopOnReturn(4);
2872   }
2873
2874   if (!Is64Bit) {
2875     // RegSaveFrameIndex is X86-64 only.
2876     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2877     if (CallConv == CallingConv::X86_FastCall ||
2878         CallConv == CallingConv::X86_ThisCall)
2879       // fastcc functions can't have varargs.
2880       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2881   }
2882
2883   FuncInfo->setArgumentStackSize(StackSize);
2884
2885   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2886     EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2887     if (Personality == EHPersonality::CoreCLR) {
2888       assert(Is64Bit);
2889       // TODO: Add a mechanism to frame lowering that will allow us to indicate
2890       // that we'd prefer this slot be allocated towards the bottom of the frame
2891       // (i.e. near the stack pointer after allocating the frame).  Every
2892       // funclet needs a copy of this slot in its (mostly empty) frame, and the
2893       // offset from the bottom of this and each funclet's frame must be the
2894       // same, so the size of funclets' (mostly empty) frames is dictated by
2895       // how far this slot is from the bottom (since they allocate just enough
2896       // space to accomodate holding this slot at the correct offset).
2897       int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2898       EHInfo->PSPSymFrameIdx = PSPSymFI;
2899     }
2900   }
2901
2902   return Chain;
2903 }
2904
2905 SDValue
2906 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2907                                     SDValue StackPtr, SDValue Arg,
2908                                     SDLoc dl, SelectionDAG &DAG,
2909                                     const CCValAssign &VA,
2910                                     ISD::ArgFlagsTy Flags) const {
2911   unsigned LocMemOffset = VA.getLocMemOffset();
2912   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2913   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2914                        StackPtr, PtrOff);
2915   if (Flags.isByVal())
2916     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2917
2918   return DAG.getStore(
2919       Chain, dl, Arg, PtrOff,
2920       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2921       false, false, 0);
2922 }
2923
2924 /// Emit a load of return address if tail call
2925 /// optimization is performed and it is required.
2926 SDValue
2927 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2928                                            SDValue &OutRetAddr, SDValue Chain,
2929                                            bool IsTailCall, bool Is64Bit,
2930                                            int FPDiff, SDLoc dl) const {
2931   // Adjust the Return address stack slot.
2932   EVT VT = getPointerTy(DAG.getDataLayout());
2933   OutRetAddr = getReturnAddressFrameIndex(DAG);
2934
2935   // Load the "old" Return address.
2936   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2937                            false, false, false, 0);
2938   return SDValue(OutRetAddr.getNode(), 1);
2939 }
2940
2941 /// Emit a store of the return address if tail call
2942 /// optimization is performed and it is required (FPDiff!=0).
2943 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2944                                         SDValue Chain, SDValue RetAddrFrIdx,
2945                                         EVT PtrVT, unsigned SlotSize,
2946                                         int FPDiff, SDLoc dl) {
2947   // Store the return address to the appropriate stack slot.
2948   if (!FPDiff) return Chain;
2949   // Calculate the new stack slot for the return address.
2950   int NewReturnAddrFI =
2951     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2952                                          false);
2953   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2954   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2955                        MachinePointerInfo::getFixedStack(
2956                            DAG.getMachineFunction(), NewReturnAddrFI),
2957                        false, false, 0);
2958   return Chain;
2959 }
2960
2961 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2962 /// operation of specified width.
2963 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
2964                        SDValue V2) {
2965   unsigned NumElems = VT.getVectorNumElements();
2966   SmallVector<int, 8> Mask;
2967   Mask.push_back(NumElems);
2968   for (unsigned i = 1; i != NumElems; ++i)
2969     Mask.push_back(i);
2970   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2971 }
2972
2973 SDValue
2974 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2975                              SmallVectorImpl<SDValue> &InVals) const {
2976   SelectionDAG &DAG                     = CLI.DAG;
2977   SDLoc &dl                             = CLI.DL;
2978   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2979   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2980   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2981   SDValue Chain                         = CLI.Chain;
2982   SDValue Callee                        = CLI.Callee;
2983   CallingConv::ID CallConv              = CLI.CallConv;
2984   bool &isTailCall                      = CLI.IsTailCall;
2985   bool isVarArg                         = CLI.IsVarArg;
2986
2987   MachineFunction &MF = DAG.getMachineFunction();
2988   bool Is64Bit        = Subtarget->is64Bit();
2989   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2990   StructReturnType SR = callIsStructReturn(Outs);
2991   bool IsSibcall      = false;
2992   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2993   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2994
2995   if (Attr.getValueAsString() == "true")
2996     isTailCall = false;
2997
2998   if (Subtarget->isPICStyleGOT() &&
2999       !MF.getTarget().Options.GuaranteedTailCallOpt) {
3000     // If we are using a GOT, disable tail calls to external symbols with
3001     // default visibility. Tail calling such a symbol requires using a GOT
3002     // relocation, which forces early binding of the symbol. This breaks code
3003     // that require lazy function symbol resolution. Using musttail or
3004     // GuaranteedTailCallOpt will override this.
3005     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3006     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3007                G->getGlobal()->hasDefaultVisibility()))
3008       isTailCall = false;
3009   }
3010
3011   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3012   if (IsMustTail) {
3013     // Force this to be a tail call.  The verifier rules are enough to ensure
3014     // that we can lower this successfully without moving the return address
3015     // around.
3016     isTailCall = true;
3017   } else if (isTailCall) {
3018     // Check if it's really possible to do a tail call.
3019     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3020                     isVarArg, SR != NotStructReturn,
3021                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3022                     Outs, OutVals, Ins, DAG);
3023
3024     // Sibcalls are automatically detected tailcalls which do not require
3025     // ABI changes.
3026     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3027       IsSibcall = true;
3028
3029     if (isTailCall)
3030       ++NumTailCalls;
3031   }
3032
3033   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3034          "Var args not supported with calling convention fastcc, ghc or hipe");
3035
3036   // Analyze operands of the call, assigning locations to each operand.
3037   SmallVector<CCValAssign, 16> ArgLocs;
3038   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3039
3040   // Allocate shadow area for Win64
3041   if (IsWin64)
3042     CCInfo.AllocateStack(32, 8);
3043
3044   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3045
3046   // Get a count of how many bytes are to be pushed on the stack.
3047   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3048   if (IsSibcall)
3049     // This is a sibcall. The memory operands are available in caller's
3050     // own caller's stack.
3051     NumBytes = 0;
3052   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3053            canGuaranteeTCO(CallConv))
3054     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3055
3056   int FPDiff = 0;
3057   if (isTailCall && !IsSibcall && !IsMustTail) {
3058     // Lower arguments at fp - stackoffset + fpdiff.
3059     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3060
3061     FPDiff = NumBytesCallerPushed - NumBytes;
3062
3063     // Set the delta of movement of the returnaddr stackslot.
3064     // But only set if delta is greater than previous delta.
3065     if (FPDiff < X86Info->getTCReturnAddrDelta())
3066       X86Info->setTCReturnAddrDelta(FPDiff);
3067   }
3068
3069   unsigned NumBytesToPush = NumBytes;
3070   unsigned NumBytesToPop = NumBytes;
3071
3072   // If we have an inalloca argument, all stack space has already been allocated
3073   // for us and be right at the top of the stack.  We don't support multiple
3074   // arguments passed in memory when using inalloca.
3075   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3076     NumBytesToPush = 0;
3077     if (!ArgLocs.back().isMemLoc())
3078       report_fatal_error("cannot use inalloca attribute on a register "
3079                          "parameter");
3080     if (ArgLocs.back().getLocMemOffset() != 0)
3081       report_fatal_error("any parameter with the inalloca attribute must be "
3082                          "the only memory argument");
3083   }
3084
3085   if (!IsSibcall)
3086     Chain = DAG.getCALLSEQ_START(
3087         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3088
3089   SDValue RetAddrFrIdx;
3090   // Load return address for tail calls.
3091   if (isTailCall && FPDiff)
3092     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3093                                     Is64Bit, FPDiff, dl);
3094
3095   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3096   SmallVector<SDValue, 8> MemOpChains;
3097   SDValue StackPtr;
3098
3099   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3100   // of tail call optimization arguments are handle later.
3101   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3102   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3103     // Skip inalloca arguments, they have already been written.
3104     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3105     if (Flags.isInAlloca())
3106       continue;
3107
3108     CCValAssign &VA = ArgLocs[i];
3109     EVT RegVT = VA.getLocVT();
3110     SDValue Arg = OutVals[i];
3111     bool isByVal = Flags.isByVal();
3112
3113     // Promote the value if needed.
3114     switch (VA.getLocInfo()) {
3115     default: llvm_unreachable("Unknown loc info!");
3116     case CCValAssign::Full: break;
3117     case CCValAssign::SExt:
3118       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3119       break;
3120     case CCValAssign::ZExt:
3121       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3122       break;
3123     case CCValAssign::AExt:
3124       if (Arg.getValueType().isVector() &&
3125           Arg.getValueType().getVectorElementType() == MVT::i1)
3126         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3127       else if (RegVT.is128BitVector()) {
3128         // Special case: passing MMX values in XMM registers.
3129         Arg = DAG.getBitcast(MVT::i64, Arg);
3130         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3131         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3132       } else
3133         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3134       break;
3135     case CCValAssign::BCvt:
3136       Arg = DAG.getBitcast(RegVT, Arg);
3137       break;
3138     case CCValAssign::Indirect: {
3139       // Store the argument.
3140       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3141       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3142       Chain = DAG.getStore(
3143           Chain, dl, Arg, SpillSlot,
3144           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3145           false, false, 0);
3146       Arg = SpillSlot;
3147       break;
3148     }
3149     }
3150
3151     if (VA.isRegLoc()) {
3152       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3153       if (isVarArg && IsWin64) {
3154         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3155         // shadow reg if callee is a varargs function.
3156         unsigned ShadowReg = 0;
3157         switch (VA.getLocReg()) {
3158         case X86::XMM0: ShadowReg = X86::RCX; break;
3159         case X86::XMM1: ShadowReg = X86::RDX; break;
3160         case X86::XMM2: ShadowReg = X86::R8; break;
3161         case X86::XMM3: ShadowReg = X86::R9; break;
3162         }
3163         if (ShadowReg)
3164           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3165       }
3166     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3167       assert(VA.isMemLoc());
3168       if (!StackPtr.getNode())
3169         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3170                                       getPointerTy(DAG.getDataLayout()));
3171       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3172                                              dl, DAG, VA, Flags));
3173     }
3174   }
3175
3176   if (!MemOpChains.empty())
3177     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3178
3179   if (Subtarget->isPICStyleGOT()) {
3180     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3181     // GOT pointer.
3182     if (!isTailCall) {
3183       RegsToPass.push_back(std::make_pair(
3184           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3185                                           getPointerTy(DAG.getDataLayout()))));
3186     } else {
3187       // If we are tail calling and generating PIC/GOT style code load the
3188       // address of the callee into ECX. The value in ecx is used as target of
3189       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3190       // for tail calls on PIC/GOT architectures. Normally we would just put the
3191       // address of GOT into ebx and then call target@PLT. But for tail calls
3192       // ebx would be restored (since ebx is callee saved) before jumping to the
3193       // target@PLT.
3194
3195       // Note: The actual moving to ECX is done further down.
3196       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3197       if (G && !G->getGlobal()->hasLocalLinkage() &&
3198           G->getGlobal()->hasDefaultVisibility())
3199         Callee = LowerGlobalAddress(Callee, DAG);
3200       else if (isa<ExternalSymbolSDNode>(Callee))
3201         Callee = LowerExternalSymbol(Callee, DAG);
3202     }
3203   }
3204
3205   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3206     // From AMD64 ABI document:
3207     // For calls that may call functions that use varargs or stdargs
3208     // (prototype-less calls or calls to functions containing ellipsis (...) in
3209     // the declaration) %al is used as hidden argument to specify the number
3210     // of SSE registers used. The contents of %al do not need to match exactly
3211     // the number of registers, but must be an ubound on the number of SSE
3212     // registers used and is in the range 0 - 8 inclusive.
3213
3214     // Count the number of XMM registers allocated.
3215     static const MCPhysReg XMMArgRegs[] = {
3216       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3217       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3218     };
3219     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3220     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3221            && "SSE registers cannot be used when SSE is disabled");
3222
3223     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3224                                         DAG.getConstant(NumXMMRegs, dl,
3225                                                         MVT::i8)));
3226   }
3227
3228   if (isVarArg && IsMustTail) {
3229     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3230     for (const auto &F : Forwards) {
3231       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3232       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3233     }
3234   }
3235
3236   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3237   // don't need this because the eligibility check rejects calls that require
3238   // shuffling arguments passed in memory.
3239   if (!IsSibcall && isTailCall) {
3240     // Force all the incoming stack arguments to be loaded from the stack
3241     // before any new outgoing arguments are stored to the stack, because the
3242     // outgoing stack slots may alias the incoming argument stack slots, and
3243     // the alias isn't otherwise explicit. This is slightly more conservative
3244     // than necessary, because it means that each store effectively depends
3245     // on every argument instead of just those arguments it would clobber.
3246     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3247
3248     SmallVector<SDValue, 8> MemOpChains2;
3249     SDValue FIN;
3250     int FI = 0;
3251     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3252       CCValAssign &VA = ArgLocs[i];
3253       if (VA.isRegLoc())
3254         continue;
3255       assert(VA.isMemLoc());
3256       SDValue Arg = OutVals[i];
3257       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3258       // Skip inalloca arguments.  They don't require any work.
3259       if (Flags.isInAlloca())
3260         continue;
3261       // Create frame index.
3262       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3263       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3264       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3265       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3266
3267       if (Flags.isByVal()) {
3268         // Copy relative to framepointer.
3269         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3270         if (!StackPtr.getNode())
3271           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3272                                         getPointerTy(DAG.getDataLayout()));
3273         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3274                              StackPtr, Source);
3275
3276         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3277                                                          ArgChain,
3278                                                          Flags, DAG, dl));
3279       } else {
3280         // Store relative to framepointer.
3281         MemOpChains2.push_back(DAG.getStore(
3282             ArgChain, dl, Arg, FIN,
3283             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3284             false, false, 0));
3285       }
3286     }
3287
3288     if (!MemOpChains2.empty())
3289       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3290
3291     // Store the return address to the appropriate stack slot.
3292     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3293                                      getPointerTy(DAG.getDataLayout()),
3294                                      RegInfo->getSlotSize(), FPDiff, dl);
3295   }
3296
3297   // Build a sequence of copy-to-reg nodes chained together with token chain
3298   // and flag operands which copy the outgoing args into registers.
3299   SDValue InFlag;
3300   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3301     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3302                              RegsToPass[i].second, InFlag);
3303     InFlag = Chain.getValue(1);
3304   }
3305
3306   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3307     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3308     // In the 64-bit large code model, we have to make all calls
3309     // through a register, since the call instruction's 32-bit
3310     // pc-relative offset may not be large enough to hold the whole
3311     // address.
3312   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3313     // If the callee is a GlobalAddress node (quite common, every direct call
3314     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3315     // it.
3316     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3317
3318     // We should use extra load for direct calls to dllimported functions in
3319     // non-JIT mode.
3320     const GlobalValue *GV = G->getGlobal();
3321     if (!GV->hasDLLImportStorageClass()) {
3322       unsigned char OpFlags = 0;
3323       bool ExtraLoad = false;
3324       unsigned WrapperKind = ISD::DELETED_NODE;
3325
3326       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3327       // external symbols most go through the PLT in PIC mode.  If the symbol
3328       // has hidden or protected visibility, or if it is static or local, then
3329       // we don't need to use the PLT - we can directly call it.
3330       if (Subtarget->isTargetELF() &&
3331           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3332           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3333         OpFlags = X86II::MO_PLT;
3334       } else if (Subtarget->isPICStyleStubAny() &&
3335                  !GV->isStrongDefinitionForLinker() &&
3336                  (!Subtarget->getTargetTriple().isMacOSX() ||
3337                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3338         // PC-relative references to external symbols should go through $stub,
3339         // unless we're building with the leopard linker or later, which
3340         // automatically synthesizes these stubs.
3341         OpFlags = X86II::MO_DARWIN_STUB;
3342       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3343                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3344         // If the function is marked as non-lazy, generate an indirect call
3345         // which loads from the GOT directly. This avoids runtime overhead
3346         // at the cost of eager binding (and one extra byte of encoding).
3347         OpFlags = X86II::MO_GOTPCREL;
3348         WrapperKind = X86ISD::WrapperRIP;
3349         ExtraLoad = true;
3350       }
3351
3352       Callee = DAG.getTargetGlobalAddress(
3353           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3354
3355       // Add a wrapper if needed.
3356       if (WrapperKind != ISD::DELETED_NODE)
3357         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3358                              getPointerTy(DAG.getDataLayout()), Callee);
3359       // Add extra indirection if needed.
3360       if (ExtraLoad)
3361         Callee = DAG.getLoad(
3362             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3363             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3364             false, 0);
3365     }
3366   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3367     unsigned char OpFlags = 0;
3368
3369     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3370     // external symbols should go through the PLT.
3371     if (Subtarget->isTargetELF() &&
3372         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3373       OpFlags = X86II::MO_PLT;
3374     } else if (Subtarget->isPICStyleStubAny() &&
3375                (!Subtarget->getTargetTriple().isMacOSX() ||
3376                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3377       // PC-relative references to external symbols should go through $stub,
3378       // unless we're building with the leopard linker or later, which
3379       // automatically synthesizes these stubs.
3380       OpFlags = X86II::MO_DARWIN_STUB;
3381     }
3382
3383     Callee = DAG.getTargetExternalSymbol(
3384         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3385   } else if (Subtarget->isTarget64BitILP32() &&
3386              Callee->getValueType(0) == MVT::i32) {
3387     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3388     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3389   }
3390
3391   // Returns a chain & a flag for retval copy to use.
3392   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3393   SmallVector<SDValue, 8> Ops;
3394
3395   if (!IsSibcall && isTailCall) {
3396     Chain = DAG.getCALLSEQ_END(Chain,
3397                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3398                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3399     InFlag = Chain.getValue(1);
3400   }
3401
3402   Ops.push_back(Chain);
3403   Ops.push_back(Callee);
3404
3405   if (isTailCall)
3406     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3407
3408   // Add argument registers to the end of the list so that they are known live
3409   // into the call.
3410   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3411     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3412                                   RegsToPass[i].second.getValueType()));
3413
3414   // Add a register mask operand representing the call-preserved registers.
3415   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3416   assert(Mask && "Missing call preserved mask for calling convention");
3417
3418   // If this is an invoke in a 32-bit function using a funclet-based
3419   // personality, assume the function clobbers all registers. If an exception
3420   // is thrown, the runtime will not restore CSRs.
3421   // FIXME: Model this more precisely so that we can register allocate across
3422   // the normal edge and spill and fill across the exceptional edge.
3423   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3424     const Function *CallerFn = MF.getFunction();
3425     EHPersonality Pers =
3426         CallerFn->hasPersonalityFn()
3427             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3428             : EHPersonality::Unknown;
3429     if (isFuncletEHPersonality(Pers))
3430       Mask = RegInfo->getNoPreservedMask();
3431   }
3432
3433   Ops.push_back(DAG.getRegisterMask(Mask));
3434
3435   if (InFlag.getNode())
3436     Ops.push_back(InFlag);
3437
3438   if (isTailCall) {
3439     // We used to do:
3440     //// If this is the first return lowered for this function, add the regs
3441     //// to the liveout set for the function.
3442     // This isn't right, although it's probably harmless on x86; liveouts
3443     // should be computed from returns not tail calls.  Consider a void
3444     // function making a tail call to a function returning int.
3445     MF.getFrameInfo()->setHasTailCall();
3446     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3447   }
3448
3449   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3450   InFlag = Chain.getValue(1);
3451
3452   // Create the CALLSEQ_END node.
3453   unsigned NumBytesForCalleeToPop;
3454   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3455                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3456     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3457   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3458            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3459            SR == StackStructReturn)
3460     // If this is a call to a struct-return function, the callee
3461     // pops the hidden struct pointer, so we have to push it back.
3462     // This is common for Darwin/X86, Linux & Mingw32 targets.
3463     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3464     NumBytesForCalleeToPop = 4;
3465   else
3466     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3467
3468   // Returns a flag for retval copy to use.
3469   if (!IsSibcall) {
3470     Chain = DAG.getCALLSEQ_END(Chain,
3471                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3472                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3473                                                      true),
3474                                InFlag, dl);
3475     InFlag = Chain.getValue(1);
3476   }
3477
3478   // Handle result values, copying them out of physregs into vregs that we
3479   // return.
3480   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3481                          Ins, dl, DAG, InVals);
3482 }
3483
3484 //===----------------------------------------------------------------------===//
3485 //                Fast Calling Convention (tail call) implementation
3486 //===----------------------------------------------------------------------===//
3487
3488 //  Like std call, callee cleans arguments, convention except that ECX is
3489 //  reserved for storing the tail called function address. Only 2 registers are
3490 //  free for argument passing (inreg). Tail call optimization is performed
3491 //  provided:
3492 //                * tailcallopt is enabled
3493 //                * caller/callee are fastcc
3494 //  On X86_64 architecture with GOT-style position independent code only local
3495 //  (within module) calls are supported at the moment.
3496 //  To keep the stack aligned according to platform abi the function
3497 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3498 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3499 //  If a tail called function callee has more arguments than the caller the
3500 //  caller needs to make sure that there is room to move the RETADDR to. This is
3501 //  achieved by reserving an area the size of the argument delta right after the
3502 //  original RETADDR, but before the saved framepointer or the spilled registers
3503 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3504 //  stack layout:
3505 //    arg1
3506 //    arg2
3507 //    RETADDR
3508 //    [ new RETADDR
3509 //      move area ]
3510 //    (possible EBP)
3511 //    ESI
3512 //    EDI
3513 //    local1 ..
3514
3515 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3516 /// requirement.
3517 unsigned
3518 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3519                                                SelectionDAG& DAG) const {
3520   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3521   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3522   unsigned StackAlignment = TFI.getStackAlignment();
3523   uint64_t AlignMask = StackAlignment - 1;
3524   int64_t Offset = StackSize;
3525   unsigned SlotSize = RegInfo->getSlotSize();
3526   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3527     // Number smaller than 12 so just add the difference.
3528     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3529   } else {
3530     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3531     Offset = ((~AlignMask) & Offset) + StackAlignment +
3532       (StackAlignment-SlotSize);
3533   }
3534   return Offset;
3535 }
3536
3537 /// Return true if the given stack call argument is already available in the
3538 /// same position (relatively) of the caller's incoming argument stack.
3539 static
3540 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3541                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3542                          const X86InstrInfo *TII) {
3543   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3544   int FI = INT_MAX;
3545   if (Arg.getOpcode() == ISD::CopyFromReg) {
3546     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3547     if (!TargetRegisterInfo::isVirtualRegister(VR))
3548       return false;
3549     MachineInstr *Def = MRI->getVRegDef(VR);
3550     if (!Def)
3551       return false;
3552     if (!Flags.isByVal()) {
3553       if (!TII->isLoadFromStackSlot(Def, FI))
3554         return false;
3555     } else {
3556       unsigned Opcode = Def->getOpcode();
3557       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3558            Opcode == X86::LEA64_32r) &&
3559           Def->getOperand(1).isFI()) {
3560         FI = Def->getOperand(1).getIndex();
3561         Bytes = Flags.getByValSize();
3562       } else
3563         return false;
3564     }
3565   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3566     if (Flags.isByVal())
3567       // ByVal argument is passed in as a pointer but it's now being
3568       // dereferenced. e.g.
3569       // define @foo(%struct.X* %A) {
3570       //   tail call @bar(%struct.X* byval %A)
3571       // }
3572       return false;
3573     SDValue Ptr = Ld->getBasePtr();
3574     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3575     if (!FINode)
3576       return false;
3577     FI = FINode->getIndex();
3578   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3579     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3580     FI = FINode->getIndex();
3581     Bytes = Flags.getByValSize();
3582   } else
3583     return false;
3584
3585   assert(FI != INT_MAX);
3586   if (!MFI->isFixedObjectIndex(FI))
3587     return false;
3588   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3589 }
3590
3591 /// Check whether the call is eligible for tail call optimization. Targets
3592 /// that want to do tail call optimization should implement this function.
3593 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3594     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3595     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3596     const SmallVectorImpl<ISD::OutputArg> &Outs,
3597     const SmallVectorImpl<SDValue> &OutVals,
3598     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3599   if (!mayTailCallThisCC(CalleeCC))
3600     return false;
3601
3602   // If -tailcallopt is specified, make fastcc functions tail-callable.
3603   MachineFunction &MF = DAG.getMachineFunction();
3604   const Function *CallerF = MF.getFunction();
3605
3606   // If the function return type is x86_fp80 and the callee return type is not,
3607   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3608   // perform a tailcall optimization here.
3609   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3610     return false;
3611
3612   CallingConv::ID CallerCC = CallerF->getCallingConv();
3613   bool CCMatch = CallerCC == CalleeCC;
3614   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3615   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3616
3617   // Win64 functions have extra shadow space for argument homing. Don't do the
3618   // sibcall if the caller and callee have mismatched expectations for this
3619   // space.
3620   if (IsCalleeWin64 != IsCallerWin64)
3621     return false;
3622
3623   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3624     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3625       return true;
3626     return false;
3627   }
3628
3629   // Look for obvious safe cases to perform tail call optimization that do not
3630   // require ABI changes. This is what gcc calls sibcall.
3631
3632   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3633   // emit a special epilogue.
3634   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3635   if (RegInfo->needsStackRealignment(MF))
3636     return false;
3637
3638   // Also avoid sibcall optimization if either caller or callee uses struct
3639   // return semantics.
3640   if (isCalleeStructRet || isCallerStructRet)
3641     return false;
3642
3643   // Do not sibcall optimize vararg calls unless all arguments are passed via
3644   // registers.
3645   if (isVarArg && !Outs.empty()) {
3646     // Optimizing for varargs on Win64 is unlikely to be safe without
3647     // additional testing.
3648     if (IsCalleeWin64 || IsCallerWin64)
3649       return false;
3650
3651     SmallVector<CCValAssign, 16> ArgLocs;
3652     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3653                    *DAG.getContext());
3654
3655     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3656     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3657       if (!ArgLocs[i].isRegLoc())
3658         return false;
3659   }
3660
3661   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3662   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3663   // this into a sibcall.
3664   bool Unused = false;
3665   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3666     if (!Ins[i].Used) {
3667       Unused = true;
3668       break;
3669     }
3670   }
3671   if (Unused) {
3672     SmallVector<CCValAssign, 16> RVLocs;
3673     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3674                    *DAG.getContext());
3675     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3676     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3677       CCValAssign &VA = RVLocs[i];
3678       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3679         return false;
3680     }
3681   }
3682
3683   // If the calling conventions do not match, then we'd better make sure the
3684   // results are returned in the same way as what the caller expects.
3685   if (!CCMatch) {
3686     SmallVector<CCValAssign, 16> RVLocs1;
3687     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3688                     *DAG.getContext());
3689     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3690
3691     SmallVector<CCValAssign, 16> RVLocs2;
3692     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3693                     *DAG.getContext());
3694     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3695
3696     if (RVLocs1.size() != RVLocs2.size())
3697       return false;
3698     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3699       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3700         return false;
3701       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3702         return false;
3703       if (RVLocs1[i].isRegLoc()) {
3704         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3705           return false;
3706       } else {
3707         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3708           return false;
3709       }
3710     }
3711   }
3712
3713   unsigned StackArgsSize = 0;
3714
3715   // If the callee takes no arguments then go on to check the results of the
3716   // call.
3717   if (!Outs.empty()) {
3718     // Check if stack adjustment is needed. For now, do not do this if any
3719     // argument is passed on the stack.
3720     SmallVector<CCValAssign, 16> ArgLocs;
3721     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3722                    *DAG.getContext());
3723
3724     // Allocate shadow area for Win64
3725     if (IsCalleeWin64)
3726       CCInfo.AllocateStack(32, 8);
3727
3728     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3729     StackArgsSize = CCInfo.getNextStackOffset();
3730
3731     if (CCInfo.getNextStackOffset()) {
3732       // Check if the arguments are already laid out in the right way as
3733       // the caller's fixed stack objects.
3734       MachineFrameInfo *MFI = MF.getFrameInfo();
3735       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3736       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3737       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3738         CCValAssign &VA = ArgLocs[i];
3739         SDValue Arg = OutVals[i];
3740         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3741         if (VA.getLocInfo() == CCValAssign::Indirect)
3742           return false;
3743         if (!VA.isRegLoc()) {
3744           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3745                                    MFI, MRI, TII))
3746             return false;
3747         }
3748       }
3749     }
3750
3751     // If the tailcall address may be in a register, then make sure it's
3752     // possible to register allocate for it. In 32-bit, the call address can
3753     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3754     // callee-saved registers are restored. These happen to be the same
3755     // registers used to pass 'inreg' arguments so watch out for those.
3756     if (!Subtarget->is64Bit() &&
3757         ((!isa<GlobalAddressSDNode>(Callee) &&
3758           !isa<ExternalSymbolSDNode>(Callee)) ||
3759          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3760       unsigned NumInRegs = 0;
3761       // In PIC we need an extra register to formulate the address computation
3762       // for the callee.
3763       unsigned MaxInRegs =
3764         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3765
3766       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3767         CCValAssign &VA = ArgLocs[i];
3768         if (!VA.isRegLoc())
3769           continue;
3770         unsigned Reg = VA.getLocReg();
3771         switch (Reg) {
3772         default: break;
3773         case X86::EAX: case X86::EDX: case X86::ECX:
3774           if (++NumInRegs == MaxInRegs)
3775             return false;
3776           break;
3777         }
3778       }
3779     }
3780   }
3781
3782   bool CalleeWillPop =
3783       X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3784                        MF.getTarget().Options.GuaranteedTailCallOpt);
3785
3786   if (unsigned BytesToPop =
3787           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3788     // If we have bytes to pop, the callee must pop them.
3789     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3790     if (!CalleePopMatches)
3791       return false;
3792   } else if (CalleeWillPop && StackArgsSize > 0) {
3793     // If we don't have bytes to pop, make sure the callee doesn't pop any.
3794     return false;
3795   }
3796
3797   return true;
3798 }
3799
3800 FastISel *
3801 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3802                                   const TargetLibraryInfo *libInfo) const {
3803   return X86::createFastISel(funcInfo, libInfo);
3804 }
3805
3806 //===----------------------------------------------------------------------===//
3807 //                           Other Lowering Hooks
3808 //===----------------------------------------------------------------------===//
3809
3810 static bool MayFoldLoad(SDValue Op) {
3811   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3812 }
3813
3814 static bool MayFoldIntoStore(SDValue Op) {
3815   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3816 }
3817
3818 static bool isTargetShuffle(unsigned Opcode) {
3819   switch(Opcode) {
3820   default: return false;
3821   case X86ISD::BLENDI:
3822   case X86ISD::PSHUFB:
3823   case X86ISD::PSHUFD:
3824   case X86ISD::PSHUFHW:
3825   case X86ISD::PSHUFLW:
3826   case X86ISD::SHUFP:
3827   case X86ISD::PALIGNR:
3828   case X86ISD::MOVLHPS:
3829   case X86ISD::MOVLHPD:
3830   case X86ISD::MOVHLPS:
3831   case X86ISD::MOVLPS:
3832   case X86ISD::MOVLPD:
3833   case X86ISD::MOVSHDUP:
3834   case X86ISD::MOVSLDUP:
3835   case X86ISD::MOVDDUP:
3836   case X86ISD::MOVSS:
3837   case X86ISD::MOVSD:
3838   case X86ISD::UNPCKL:
3839   case X86ISD::UNPCKH:
3840   case X86ISD::VPERMILPI:
3841   case X86ISD::VPERM2X128:
3842   case X86ISD::VPERMI:
3843   case X86ISD::VPERMV:
3844   case X86ISD::VPERMV3:
3845     return true;
3846   }
3847 }
3848
3849 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3850                                     SDValue V1, unsigned TargetMask,
3851                                     SelectionDAG &DAG) {
3852   switch(Opc) {
3853   default: llvm_unreachable("Unknown x86 shuffle node");
3854   case X86ISD::PSHUFD:
3855   case X86ISD::PSHUFHW:
3856   case X86ISD::PSHUFLW:
3857   case X86ISD::VPERMILPI:
3858   case X86ISD::VPERMI:
3859     return DAG.getNode(Opc, dl, VT, V1,
3860                        DAG.getConstant(TargetMask, dl, MVT::i8));
3861   }
3862 }
3863
3864 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3865                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3866   switch(Opc) {
3867   default: llvm_unreachable("Unknown x86 shuffle node");
3868   case X86ISD::MOVLHPS:
3869   case X86ISD::MOVLHPD:
3870   case X86ISD::MOVHLPS:
3871   case X86ISD::MOVLPS:
3872   case X86ISD::MOVLPD:
3873   case X86ISD::MOVSS:
3874   case X86ISD::MOVSD:
3875   case X86ISD::UNPCKL:
3876   case X86ISD::UNPCKH:
3877     return DAG.getNode(Opc, dl, VT, V1, V2);
3878   }
3879 }
3880
3881 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3882   MachineFunction &MF = DAG.getMachineFunction();
3883   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3884   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3885   int ReturnAddrIndex = FuncInfo->getRAIndex();
3886
3887   if (ReturnAddrIndex == 0) {
3888     // Set up a frame object for the return address.
3889     unsigned SlotSize = RegInfo->getSlotSize();
3890     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3891                                                            -(int64_t)SlotSize,
3892                                                            false);
3893     FuncInfo->setRAIndex(ReturnAddrIndex);
3894   }
3895
3896   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3897 }
3898
3899 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3900                                        bool hasSymbolicDisplacement) {
3901   // Offset should fit into 32 bit immediate field.
3902   if (!isInt<32>(Offset))
3903     return false;
3904
3905   // If we don't have a symbolic displacement - we don't have any extra
3906   // restrictions.
3907   if (!hasSymbolicDisplacement)
3908     return true;
3909
3910   // FIXME: Some tweaks might be needed for medium code model.
3911   if (M != CodeModel::Small && M != CodeModel::Kernel)
3912     return false;
3913
3914   // For small code model we assume that latest object is 16MB before end of 31
3915   // bits boundary. We may also accept pretty large negative constants knowing
3916   // that all objects are in the positive half of address space.
3917   if (M == CodeModel::Small && Offset < 16*1024*1024)
3918     return true;
3919
3920   // For kernel code model we know that all object resist in the negative half
3921   // of 32bits address space. We may not accept negative offsets, since they may
3922   // be just off and we may accept pretty large positive ones.
3923   if (M == CodeModel::Kernel && Offset >= 0)
3924     return true;
3925
3926   return false;
3927 }
3928
3929 /// Determines whether the callee is required to pop its own arguments.
3930 /// Callee pop is necessary to support tail calls.
3931 bool X86::isCalleePop(CallingConv::ID CallingConv,
3932                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3933   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3934   // can guarantee TCO.
3935   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3936     return true;
3937
3938   switch (CallingConv) {
3939   default:
3940     return false;
3941   case CallingConv::X86_StdCall:
3942   case CallingConv::X86_FastCall:
3943   case CallingConv::X86_ThisCall:
3944   case CallingConv::X86_VectorCall:
3945     return !is64Bit;
3946   }
3947 }
3948
3949 /// \brief Return true if the condition is an unsigned comparison operation.
3950 static bool isX86CCUnsigned(unsigned X86CC) {
3951   switch (X86CC) {
3952   default: llvm_unreachable("Invalid integer condition!");
3953   case X86::COND_E:     return true;
3954   case X86::COND_G:     return false;
3955   case X86::COND_GE:    return false;
3956   case X86::COND_L:     return false;
3957   case X86::COND_LE:    return false;
3958   case X86::COND_NE:    return true;
3959   case X86::COND_B:     return true;
3960   case X86::COND_A:     return true;
3961   case X86::COND_BE:    return true;
3962   case X86::COND_AE:    return true;
3963   }
3964 }
3965
3966 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
3967   switch (SetCCOpcode) {
3968   default: llvm_unreachable("Invalid integer condition!");
3969   case ISD::SETEQ:  return X86::COND_E;
3970   case ISD::SETGT:  return X86::COND_G;
3971   case ISD::SETGE:  return X86::COND_GE;
3972   case ISD::SETLT:  return X86::COND_L;
3973   case ISD::SETLE:  return X86::COND_LE;
3974   case ISD::SETNE:  return X86::COND_NE;
3975   case ISD::SETULT: return X86::COND_B;
3976   case ISD::SETUGT: return X86::COND_A;
3977   case ISD::SETULE: return X86::COND_BE;
3978   case ISD::SETUGE: return X86::COND_AE;
3979   }
3980 }
3981
3982 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3983 /// condition code, returning the condition code and the LHS/RHS of the
3984 /// comparison to make.
3985 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3986                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3987   if (!isFP) {
3988     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3989       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3990         // X > -1   -> X == 0, jump !sign.
3991         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3992         return X86::COND_NS;
3993       }
3994       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3995         // X < 0   -> X == 0, jump on sign.
3996         return X86::COND_S;
3997       }
3998       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3999         // X < 1   -> X <= 0
4000         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4001         return X86::COND_LE;
4002       }
4003     }
4004
4005     return TranslateIntegerX86CC(SetCCOpcode);
4006   }
4007
4008   // First determine if it is required or is profitable to flip the operands.
4009
4010   // If LHS is a foldable load, but RHS is not, flip the condition.
4011   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4012       !ISD::isNON_EXTLoad(RHS.getNode())) {
4013     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4014     std::swap(LHS, RHS);
4015   }
4016
4017   switch (SetCCOpcode) {
4018   default: break;
4019   case ISD::SETOLT:
4020   case ISD::SETOLE:
4021   case ISD::SETUGT:
4022   case ISD::SETUGE:
4023     std::swap(LHS, RHS);
4024     break;
4025   }
4026
4027   // On a floating point condition, the flags are set as follows:
4028   // ZF  PF  CF   op
4029   //  0 | 0 | 0 | X > Y
4030   //  0 | 0 | 1 | X < Y
4031   //  1 | 0 | 0 | X == Y
4032   //  1 | 1 | 1 | unordered
4033   switch (SetCCOpcode) {
4034   default: llvm_unreachable("Condcode should be pre-legalized away");
4035   case ISD::SETUEQ:
4036   case ISD::SETEQ:   return X86::COND_E;
4037   case ISD::SETOLT:              // flipped
4038   case ISD::SETOGT:
4039   case ISD::SETGT:   return X86::COND_A;
4040   case ISD::SETOLE:              // flipped
4041   case ISD::SETOGE:
4042   case ISD::SETGE:   return X86::COND_AE;
4043   case ISD::SETUGT:              // flipped
4044   case ISD::SETULT:
4045   case ISD::SETLT:   return X86::COND_B;
4046   case ISD::SETUGE:              // flipped
4047   case ISD::SETULE:
4048   case ISD::SETLE:   return X86::COND_BE;
4049   case ISD::SETONE:
4050   case ISD::SETNE:   return X86::COND_NE;
4051   case ISD::SETUO:   return X86::COND_P;
4052   case ISD::SETO:    return X86::COND_NP;
4053   case ISD::SETOEQ:
4054   case ISD::SETUNE:  return X86::COND_INVALID;
4055   }
4056 }
4057
4058 /// Is there a floating point cmov for the specific X86 condition code?
4059 /// Current x86 isa includes the following FP cmov instructions:
4060 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4061 static bool hasFPCMov(unsigned X86CC) {
4062   switch (X86CC) {
4063   default:
4064     return false;
4065   case X86::COND_B:
4066   case X86::COND_BE:
4067   case X86::COND_E:
4068   case X86::COND_P:
4069   case X86::COND_A:
4070   case X86::COND_AE:
4071   case X86::COND_NE:
4072   case X86::COND_NP:
4073     return true;
4074   }
4075 }
4076
4077 /// Returns true if the target can instruction select the
4078 /// specified FP immediate natively. If false, the legalizer will
4079 /// materialize the FP immediate as a load from a constant pool.
4080 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4081   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4082     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4083       return true;
4084   }
4085   return false;
4086 }
4087
4088 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4089                                               ISD::LoadExtType ExtTy,
4090                                               EVT NewVT) const {
4091   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4092   // relocation target a movq or addq instruction: don't let the load shrink.
4093   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4094   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4095     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4096       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4097   return true;
4098 }
4099
4100 /// \brief Returns true if it is beneficial to convert a load of a constant
4101 /// to just the constant itself.
4102 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4103                                                           Type *Ty) const {
4104   assert(Ty->isIntegerTy());
4105
4106   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4107   if (BitSize == 0 || BitSize > 64)
4108     return false;
4109   return true;
4110 }
4111
4112 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4113                                                 unsigned Index) const {
4114   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4115     return false;
4116
4117   return (Index == 0 || Index == ResVT.getVectorNumElements());
4118 }
4119
4120 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4121   // Speculate cttz only if we can directly use TZCNT.
4122   return Subtarget->hasBMI();
4123 }
4124
4125 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4126   // Speculate ctlz only if we can directly use LZCNT.
4127   return Subtarget->hasLZCNT();
4128 }
4129
4130 /// Return true if every element in Mask, beginning
4131 /// from position Pos and ending in Pos+Size is undef.
4132 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4133   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4134     if (0 <= Mask[i])
4135       return false;
4136   return true;
4137 }
4138
4139 /// Return true if Val is undef or if its value falls within the
4140 /// specified range (L, H].
4141 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4142   return (Val < 0) || (Val >= Low && Val < Hi);
4143 }
4144
4145 /// Val is either less than zero (undef) or equal to the specified value.
4146 static bool isUndefOrEqual(int Val, int CmpVal) {
4147   return (Val < 0 || Val == CmpVal);
4148 }
4149
4150 /// Return true if every element in Mask, beginning
4151 /// from position Pos and ending in Pos+Size, falls within the specified
4152 /// sequential range (Low, Low+Size]. or is undef.
4153 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4154                                        unsigned Pos, unsigned Size, int Low) {
4155   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4156     if (!isUndefOrEqual(Mask[i], Low))
4157       return false;
4158   return true;
4159 }
4160
4161 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4162 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4163 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4164   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4165   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4166     return false;
4167
4168   // The index should be aligned on a vecWidth-bit boundary.
4169   uint64_t Index =
4170     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4171
4172   MVT VT = N->getSimpleValueType(0);
4173   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4174   bool Result = (Index * ElSize) % vecWidth == 0;
4175
4176   return Result;
4177 }
4178
4179 /// Return true if the specified INSERT_SUBVECTOR
4180 /// operand specifies a subvector insert that is suitable for input to
4181 /// insertion of 128 or 256-bit subvectors
4182 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4183   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4184   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4185     return false;
4186   // The index should be aligned on a vecWidth-bit boundary.
4187   uint64_t Index =
4188     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4189
4190   MVT VT = N->getSimpleValueType(0);
4191   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4192   bool Result = (Index * ElSize) % vecWidth == 0;
4193
4194   return Result;
4195 }
4196
4197 bool X86::isVINSERT128Index(SDNode *N) {
4198   return isVINSERTIndex(N, 128);
4199 }
4200
4201 bool X86::isVINSERT256Index(SDNode *N) {
4202   return isVINSERTIndex(N, 256);
4203 }
4204
4205 bool X86::isVEXTRACT128Index(SDNode *N) {
4206   return isVEXTRACTIndex(N, 128);
4207 }
4208
4209 bool X86::isVEXTRACT256Index(SDNode *N) {
4210   return isVEXTRACTIndex(N, 256);
4211 }
4212
4213 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4214   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4215   assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4216          "Illegal extract subvector for VEXTRACT");
4217
4218   uint64_t Index =
4219     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4220
4221   MVT VecVT = N->getOperand(0).getSimpleValueType();
4222   MVT ElVT = VecVT.getVectorElementType();
4223
4224   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4225   return Index / NumElemsPerChunk;
4226 }
4227
4228 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4229   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4230   assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4231          "Illegal insert subvector for VINSERT");
4232
4233   uint64_t Index =
4234     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4235
4236   MVT VecVT = N->getSimpleValueType(0);
4237   MVT ElVT = VecVT.getVectorElementType();
4238
4239   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4240   return Index / NumElemsPerChunk;
4241 }
4242
4243 /// Return the appropriate immediate to extract the specified
4244 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4245 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4246   return getExtractVEXTRACTImmediate(N, 128);
4247 }
4248
4249 /// Return the appropriate immediate to extract the specified
4250 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4251 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4252   return getExtractVEXTRACTImmediate(N, 256);
4253 }
4254
4255 /// Return the appropriate immediate to insert at the specified
4256 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4257 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4258   return getInsertVINSERTImmediate(N, 128);
4259 }
4260
4261 /// Return the appropriate immediate to insert at the specified
4262 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4263 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4264   return getInsertVINSERTImmediate(N, 256);
4265 }
4266
4267 /// Returns true if V is a constant integer zero.
4268 static bool isZero(SDValue V) {
4269   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4270   return C && C->isNullValue();
4271 }
4272
4273 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4274 bool X86::isZeroNode(SDValue Elt) {
4275   if (isZero(Elt))
4276     return true;
4277   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4278     return CFP->getValueAPF().isPosZero();
4279   return false;
4280 }
4281
4282 // Build a vector of constants
4283 // Use an UNDEF node if MaskElt == -1.
4284 // Spilt 64-bit constants in the 32-bit mode.
4285 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4286                               SelectionDAG &DAG,
4287                               SDLoc dl, bool IsMask = false) {
4288
4289   SmallVector<SDValue, 32>  Ops;
4290   bool Split = false;
4291
4292   MVT ConstVecVT = VT;
4293   unsigned NumElts = VT.getVectorNumElements();
4294   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4295   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4296     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4297     Split = true;
4298   }
4299
4300   MVT EltVT = ConstVecVT.getVectorElementType();
4301   for (unsigned i = 0; i < NumElts; ++i) {
4302     bool IsUndef = Values[i] < 0 && IsMask;
4303     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4304       DAG.getConstant(Values[i], dl, EltVT);
4305     Ops.push_back(OpNode);
4306     if (Split)
4307       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4308                     DAG.getConstant(0, dl, EltVT));
4309   }
4310   SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4311   if (Split)
4312     ConstsNode = DAG.getBitcast(VT, ConstsNode);
4313   return ConstsNode;
4314 }
4315
4316 /// Returns a vector of specified type with all zero elements.
4317 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4318                              SelectionDAG &DAG, SDLoc dl) {
4319   assert(VT.isVector() && "Expected a vector type");
4320
4321   // Always build SSE zero vectors as <4 x i32> bitcasted
4322   // to their dest type. This ensures they get CSE'd.
4323   SDValue Vec;
4324   if (VT.is128BitVector()) {  // SSE
4325     if (Subtarget->hasSSE2()) {  // SSE2
4326       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4327       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4328     } else { // SSE1
4329       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4330       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4331     }
4332   } else if (VT.is256BitVector()) { // AVX
4333     if (Subtarget->hasInt256()) { // AVX2
4334       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4335       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4336       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4337     } else {
4338       // 256-bit logic and arithmetic instructions in AVX are all
4339       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4340       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4341       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4342       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4343     }
4344   } else if (VT.is512BitVector()) { // AVX-512
4345       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4346       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4347                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4348       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4349   } else if (VT.getVectorElementType() == MVT::i1) {
4350
4351     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4352             && "Unexpected vector type");
4353     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4354             && "Unexpected vector type");
4355     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4356     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4357     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4358   } else
4359     llvm_unreachable("Unexpected vector type");
4360
4361   return DAG.getBitcast(VT, Vec);
4362 }
4363
4364 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4365                                 SelectionDAG &DAG, SDLoc dl,
4366                                 unsigned vectorWidth) {
4367   assert((vectorWidth == 128 || vectorWidth == 256) &&
4368          "Unsupported vector width");
4369   EVT VT = Vec.getValueType();
4370   EVT ElVT = VT.getVectorElementType();
4371   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4372   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4373                                   VT.getVectorNumElements()/Factor);
4374
4375   // Extract from UNDEF is UNDEF.
4376   if (Vec.getOpcode() == ISD::UNDEF)
4377     return DAG.getUNDEF(ResultVT);
4378
4379   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4380   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4381   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4382
4383   // This is the index of the first element of the vectorWidth-bit chunk
4384   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4385   IdxVal &= ~(ElemsPerChunk - 1);
4386
4387   // If the input is a buildvector just emit a smaller one.
4388   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4389     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4390                        makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4391
4392   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4393   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4394 }
4395
4396 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4397 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4398 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4399 /// instructions or a simple subregister reference. Idx is an index in the
4400 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4401 /// lowering EXTRACT_VECTOR_ELT operations easier.
4402 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4403                                    SelectionDAG &DAG, SDLoc dl) {
4404   assert((Vec.getValueType().is256BitVector() ||
4405           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4406   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4407 }
4408
4409 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4410 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4411                                    SelectionDAG &DAG, SDLoc dl) {
4412   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4413   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4414 }
4415
4416 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4417                                unsigned IdxVal, SelectionDAG &DAG,
4418                                SDLoc dl, unsigned vectorWidth) {
4419   assert((vectorWidth == 128 || vectorWidth == 256) &&
4420          "Unsupported vector width");
4421   // Inserting UNDEF is Result
4422   if (Vec.getOpcode() == ISD::UNDEF)
4423     return Result;
4424   EVT VT = Vec.getValueType();
4425   EVT ElVT = VT.getVectorElementType();
4426   EVT ResultVT = Result.getValueType();
4427
4428   // Insert the relevant vectorWidth bits.
4429   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4430   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4431
4432   // This is the index of the first element of the vectorWidth-bit chunk
4433   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4434   IdxVal &= ~(ElemsPerChunk - 1);
4435
4436   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4437   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4438 }
4439
4440 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4441 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4442 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4443 /// simple superregister reference.  Idx is an index in the 128 bits
4444 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4445 /// lowering INSERT_VECTOR_ELT operations easier.
4446 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4447                                   SelectionDAG &DAG, SDLoc dl) {
4448   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4449
4450   // For insertion into the zero index (low half) of a 256-bit vector, it is
4451   // more efficient to generate a blend with immediate instead of an insert*128.
4452   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4453   // extend the subvector to the size of the result vector. Make sure that
4454   // we are not recursing on that node by checking for undef here.
4455   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4456       Result.getOpcode() != ISD::UNDEF) {
4457     EVT ResultVT = Result.getValueType();
4458     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4459     SDValue Undef = DAG.getUNDEF(ResultVT);
4460     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4461                                  Vec, ZeroIndex);
4462
4463     // The blend instruction, and therefore its mask, depend on the data type.
4464     MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4465     if (ScalarType.isFloatingPoint()) {
4466       // Choose either vblendps (float) or vblendpd (double).
4467       unsigned ScalarSize = ScalarType.getSizeInBits();
4468       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4469       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4470       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4471       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4472     }
4473
4474     const X86Subtarget &Subtarget =
4475     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4476
4477     // AVX2 is needed for 256-bit integer blend support.
4478     // Integers must be cast to 32-bit because there is only vpblendd;
4479     // vpblendw can't be used for this because it has a handicapped mask.
4480
4481     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4482     // is still more efficient than using the wrong domain vinsertf128 that
4483     // will be created by InsertSubVector().
4484     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4485
4486     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4487     Vec256 = DAG.getBitcast(CastVT, Vec256);
4488     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4489     return DAG.getBitcast(ResultVT, Vec256);
4490   }
4491
4492   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4493 }
4494
4495 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4496                                   SelectionDAG &DAG, SDLoc dl) {
4497   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4498   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4499 }
4500
4501 /// Insert i1-subvector to i1-vector.
4502 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4503
4504   SDLoc dl(Op);
4505   SDValue Vec = Op.getOperand(0);
4506   SDValue SubVec = Op.getOperand(1);
4507   SDValue Idx = Op.getOperand(2);
4508
4509   if (!isa<ConstantSDNode>(Idx))
4510     return SDValue();
4511
4512   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4513   if (IdxVal == 0  && Vec.isUndef()) // the operation is legal
4514     return Op;
4515
4516   MVT OpVT = Op.getSimpleValueType();
4517   MVT SubVecVT = SubVec.getSimpleValueType();
4518   unsigned NumElems = OpVT.getVectorNumElements();
4519   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4520
4521   assert(IdxVal + SubVecNumElems <= NumElems &&
4522          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4523          "Unexpected index value in INSERT_SUBVECTOR");
4524
4525   // There are 3 possible cases:
4526   // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4527   // 2. Subvector should be inserted in the upper part
4528   //    (IdxVal + SubVecNumElems == NumElems)
4529   // 3. Subvector should be inserted in the middle (for example v2i1
4530   //    to v16i1, index 2)
4531
4532   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4533   SDValue Undef = DAG.getUNDEF(OpVT);
4534   SDValue WideSubVec =
4535     DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4536   if (Vec.isUndef())
4537     return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4538       DAG.getConstant(IdxVal, dl, MVT::i8));
4539
4540   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4541     unsigned ShiftLeft = NumElems - SubVecNumElems;
4542     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4543     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4544       DAG.getConstant(ShiftLeft, dl, MVT::i8));
4545     return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4546       DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4547   }
4548
4549   if (IdxVal == 0) {
4550     // Zero lower bits of the Vec
4551     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4552     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4553     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4554     // Merge them together
4555     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4556   }
4557
4558   // Simple case when we put subvector in the upper part
4559   if (IdxVal + SubVecNumElems == NumElems) {
4560     // Zero upper bits of the Vec
4561     WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4562                         DAG.getConstant(IdxVal, dl, MVT::i8));
4563     SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4564     Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4565     Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4566     return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4567   }
4568   // Subvector should be inserted in the middle - use shuffle
4569   SmallVector<int, 64> Mask;
4570   for (unsigned i = 0; i < NumElems; ++i)
4571     Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4572                     i : i + NumElems);
4573   return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4574 }
4575
4576 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4577 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4578 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4579 /// large BUILD_VECTORS.
4580 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4581                                    unsigned NumElems, SelectionDAG &DAG,
4582                                    SDLoc dl) {
4583   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4584   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4585 }
4586
4587 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4588                                    unsigned NumElems, SelectionDAG &DAG,
4589                                    SDLoc dl) {
4590   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4591   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4592 }
4593
4594 /// Returns a vector of specified type with all bits set.
4595 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4596 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4597 /// Then bitcast to their original type, ensuring they get CSE'd.
4598 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4599                              SelectionDAG &DAG, SDLoc dl) {
4600   assert(VT.isVector() && "Expected a vector type");
4601
4602   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4603   SDValue Vec;
4604   if (VT.is512BitVector()) {
4605     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4606                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4607     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4608   } else if (VT.is256BitVector()) {
4609     if (Subtarget->hasInt256()) { // AVX2
4610       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4611       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4612     } else { // AVX
4613       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4614       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4615     }
4616   } else if (VT.is128BitVector()) {
4617     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4618   } else
4619     llvm_unreachable("Unexpected vector type");
4620
4621   return DAG.getBitcast(VT, Vec);
4622 }
4623
4624 /// Returns a vector_shuffle node for an unpackl operation.
4625 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4626                           SDValue V2) {
4627   unsigned NumElems = VT.getVectorNumElements();
4628   SmallVector<int, 8> Mask;
4629   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4630     Mask.push_back(i);
4631     Mask.push_back(i + NumElems);
4632   }
4633   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4634 }
4635
4636 /// Returns a vector_shuffle node for an unpackh operation.
4637 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4638                           SDValue V2) {
4639   unsigned NumElems = VT.getVectorNumElements();
4640   SmallVector<int, 8> Mask;
4641   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4642     Mask.push_back(i + Half);
4643     Mask.push_back(i + NumElems + Half);
4644   }
4645   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4646 }
4647
4648 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4649 /// This produces a shuffle where the low element of V2 is swizzled into the
4650 /// zero/undef vector, landing at element Idx.
4651 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4652 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4653                                            bool IsZero,
4654                                            const X86Subtarget *Subtarget,
4655                                            SelectionDAG &DAG) {
4656   MVT VT = V2.getSimpleValueType();
4657   SDValue V1 = IsZero
4658     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4659   unsigned NumElems = VT.getVectorNumElements();
4660   SmallVector<int, 16> MaskVec;
4661   for (unsigned i = 0; i != NumElems; ++i)
4662     // If this is the insertion idx, put the low elt of V2 here.
4663     MaskVec.push_back(i == Idx ? NumElems : i);
4664   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4665 }
4666
4667 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4668 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4669 /// uses one source. Note that this will set IsUnary for shuffles which use a
4670 /// single input multiple times, and in those cases it will
4671 /// adjust the mask to only have indices within that single input.
4672 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4673 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4674                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4675   unsigned NumElems = VT.getVectorNumElements();
4676   SDValue ImmN;
4677
4678   IsUnary = false;
4679   bool IsFakeUnary = false;
4680   switch(N->getOpcode()) {
4681   case X86ISD::BLENDI:
4682     ImmN = N->getOperand(N->getNumOperands()-1);
4683     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4684     break;
4685   case X86ISD::SHUFP:
4686     ImmN = N->getOperand(N->getNumOperands()-1);
4687     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4688     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4689     break;
4690   case X86ISD::UNPCKH:
4691     DecodeUNPCKHMask(VT, Mask);
4692     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4693     break;
4694   case X86ISD::UNPCKL:
4695     DecodeUNPCKLMask(VT, Mask);
4696     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4697     break;
4698   case X86ISD::MOVHLPS:
4699     DecodeMOVHLPSMask(NumElems, Mask);
4700     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4701     break;
4702   case X86ISD::MOVLHPS:
4703     DecodeMOVLHPSMask(NumElems, Mask);
4704     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4705     break;
4706   case X86ISD::PALIGNR:
4707     ImmN = N->getOperand(N->getNumOperands()-1);
4708     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4709     break;
4710   case X86ISD::PSHUFD:
4711   case X86ISD::VPERMILPI:
4712     ImmN = N->getOperand(N->getNumOperands()-1);
4713     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4714     IsUnary = true;
4715     break;
4716   case X86ISD::PSHUFHW:
4717     ImmN = N->getOperand(N->getNumOperands()-1);
4718     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4719     IsUnary = true;
4720     break;
4721   case X86ISD::PSHUFLW:
4722     ImmN = N->getOperand(N->getNumOperands()-1);
4723     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4724     IsUnary = true;
4725     break;
4726   case X86ISD::PSHUFB: {
4727     IsUnary = true;
4728     SDValue MaskNode = N->getOperand(1);
4729     while (MaskNode->getOpcode() == ISD::BITCAST)
4730       MaskNode = MaskNode->getOperand(0);
4731
4732     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4733       // If we have a build-vector, then things are easy.
4734       MVT VT = MaskNode.getSimpleValueType();
4735       assert(VT.isVector() &&
4736              "Can't produce a non-vector with a build_vector!");
4737       if (!VT.isInteger())
4738         return false;
4739
4740       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4741
4742       SmallVector<uint64_t, 32> RawMask;
4743       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4744         SDValue Op = MaskNode->getOperand(i);
4745         if (Op->getOpcode() == ISD::UNDEF) {
4746           RawMask.push_back((uint64_t)SM_SentinelUndef);
4747           continue;
4748         }
4749         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4750         if (!CN)
4751           return false;
4752         APInt MaskElement = CN->getAPIntValue();
4753
4754         // We now have to decode the element which could be any integer size and
4755         // extract each byte of it.
4756         for (int j = 0; j < NumBytesPerElement; ++j) {
4757           // Note that this is x86 and so always little endian: the low byte is
4758           // the first byte of the mask.
4759           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4760           MaskElement = MaskElement.lshr(8);
4761         }
4762       }
4763       DecodePSHUFBMask(RawMask, Mask);
4764       break;
4765     }
4766
4767     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4768     if (!MaskLoad)
4769       return false;
4770
4771     SDValue Ptr = MaskLoad->getBasePtr();
4772     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4773         Ptr->getOpcode() == X86ISD::WrapperRIP)
4774       Ptr = Ptr->getOperand(0);
4775
4776     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4777     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4778       return false;
4779
4780     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4781       DecodePSHUFBMask(C, Mask);
4782       if (Mask.empty())
4783         return false;
4784       break;
4785     }
4786
4787     return false;
4788   }
4789   case X86ISD::VPERMI:
4790     ImmN = N->getOperand(N->getNumOperands()-1);
4791     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4792     IsUnary = true;
4793     break;
4794   case X86ISD::MOVSS:
4795   case X86ISD::MOVSD:
4796     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4797     break;
4798   case X86ISD::VPERM2X128:
4799     ImmN = N->getOperand(N->getNumOperands()-1);
4800     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4801     if (Mask.empty()) return false;
4802     // Mask only contains negative index if an element is zero.
4803     if (std::any_of(Mask.begin(), Mask.end(),
4804                     [](int M){ return M == SM_SentinelZero; }))
4805       return false;
4806     break;
4807   case X86ISD::MOVSLDUP:
4808     DecodeMOVSLDUPMask(VT, Mask);
4809     IsUnary = true;
4810     break;
4811   case X86ISD::MOVSHDUP:
4812     DecodeMOVSHDUPMask(VT, Mask);
4813     IsUnary = true;
4814     break;
4815   case X86ISD::MOVDDUP:
4816     DecodeMOVDDUPMask(VT, Mask);
4817     IsUnary = true;
4818     break;
4819   case X86ISD::MOVLHPD:
4820   case X86ISD::MOVLPD:
4821   case X86ISD::MOVLPS:
4822     // Not yet implemented
4823     return false;
4824   case X86ISD::VPERMV: {
4825     IsUnary = true;
4826     SDValue MaskNode = N->getOperand(0);
4827     while (MaskNode->getOpcode() == ISD::BITCAST)
4828       MaskNode = MaskNode->getOperand(0);
4829
4830     unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4831     SmallVector<uint64_t, 32> RawMask;
4832     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4833       // If we have a build-vector, then things are easy.
4834       assert(MaskNode.getSimpleValueType().isInteger() &&
4835              MaskNode.getSimpleValueType().getVectorNumElements() ==
4836              VT.getVectorNumElements());
4837
4838       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4839         SDValue Op = MaskNode->getOperand(i);
4840         if (Op->getOpcode() == ISD::UNDEF)
4841           RawMask.push_back((uint64_t)SM_SentinelUndef);
4842         else if (isa<ConstantSDNode>(Op)) {
4843           APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4844           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4845         } else
4846           return false;
4847       }
4848       DecodeVPERMVMask(RawMask, Mask);
4849       break;
4850     }
4851     if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4852       unsigned NumEltsInMask = MaskNode->getNumOperands();
4853       MaskNode = MaskNode->getOperand(0);
4854       auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4855       if (CN) {
4856         APInt MaskEltValue = CN->getAPIntValue();
4857         for (unsigned i = 0; i < NumEltsInMask; ++i)
4858           RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4859         DecodeVPERMVMask(RawMask, Mask);
4860         break;
4861       }
4862       // It may be a scalar load
4863     }
4864
4865     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4866     if (!MaskLoad)
4867       return false;
4868
4869     SDValue Ptr = MaskLoad->getBasePtr();
4870     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4871         Ptr->getOpcode() == X86ISD::WrapperRIP)
4872       Ptr = Ptr->getOperand(0);
4873
4874     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4875     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4876       return false;
4877
4878     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4879     if (C) {
4880       DecodeVPERMVMask(C, VT, Mask);
4881       if (Mask.empty())
4882         return false;
4883       break;
4884     }
4885     return false;
4886   }
4887   case X86ISD::VPERMV3: {
4888     IsUnary = false;
4889     SDValue MaskNode = N->getOperand(1);
4890     while (MaskNode->getOpcode() == ISD::BITCAST)
4891       MaskNode = MaskNode->getOperand(1);
4892
4893     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4894       // If we have a build-vector, then things are easy.
4895       assert(MaskNode.getSimpleValueType().isInteger() &&
4896              MaskNode.getSimpleValueType().getVectorNumElements() ==
4897              VT.getVectorNumElements());
4898
4899       SmallVector<uint64_t, 32> RawMask;
4900       unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4901
4902       for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4903         SDValue Op = MaskNode->getOperand(i);
4904         if (Op->getOpcode() == ISD::UNDEF)
4905           RawMask.push_back((uint64_t)SM_SentinelUndef);
4906         else {
4907           auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4908           if (!CN)
4909             return false;
4910           APInt MaskElement = CN->getAPIntValue();
4911           RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4912         }
4913       }
4914       DecodeVPERMV3Mask(RawMask, Mask);
4915       break;
4916     }
4917
4918     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4919     if (!MaskLoad)
4920       return false;
4921
4922     SDValue Ptr = MaskLoad->getBasePtr();
4923     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4924         Ptr->getOpcode() == X86ISD::WrapperRIP)
4925       Ptr = Ptr->getOperand(0);
4926
4927     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4928     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4929       return false;
4930
4931     auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4932     if (C) {
4933       DecodeVPERMV3Mask(C, VT, Mask);
4934       if (Mask.empty())
4935         return false;
4936       break;
4937     }
4938     return false;
4939   }
4940   default: llvm_unreachable("unknown target shuffle node");
4941   }
4942
4943   // If we have a fake unary shuffle, the shuffle mask is spread across two
4944   // inputs that are actually the same node. Re-map the mask to always point
4945   // into the first input.
4946   if (IsFakeUnary)
4947     for (int &M : Mask)
4948       if (M >= (int)Mask.size())
4949         M -= Mask.size();
4950
4951   return true;
4952 }
4953
4954 /// Returns the scalar element that will make up the ith
4955 /// element of the result of the vector shuffle.
4956 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4957                                    unsigned Depth) {
4958   if (Depth == 6)
4959     return SDValue();  // Limit search depth.
4960
4961   SDValue V = SDValue(N, 0);
4962   EVT VT = V.getValueType();
4963   unsigned Opcode = V.getOpcode();
4964
4965   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4966   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4967     int Elt = SV->getMaskElt(Index);
4968
4969     if (Elt < 0)
4970       return DAG.getUNDEF(VT.getVectorElementType());
4971
4972     unsigned NumElems = VT.getVectorNumElements();
4973     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4974                                          : SV->getOperand(1);
4975     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4976   }
4977
4978   // Recurse into target specific vector shuffles to find scalars.
4979   if (isTargetShuffle(Opcode)) {
4980     MVT ShufVT = V.getSimpleValueType();
4981     unsigned NumElems = ShufVT.getVectorNumElements();
4982     SmallVector<int, 16> ShuffleMask;
4983     bool IsUnary;
4984
4985     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4986       return SDValue();
4987
4988     int Elt = ShuffleMask[Index];
4989     if (Elt < 0)
4990       return DAG.getUNDEF(ShufVT.getVectorElementType());
4991
4992     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4993                                          : N->getOperand(1);
4994     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4995                                Depth+1);
4996   }
4997
4998   // Actual nodes that may contain scalar elements
4999   if (Opcode == ISD::BITCAST) {
5000     V = V.getOperand(0);
5001     EVT SrcVT = V.getValueType();
5002     unsigned NumElems = VT.getVectorNumElements();
5003
5004     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5005       return SDValue();
5006   }
5007
5008   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5009     return (Index == 0) ? V.getOperand(0)
5010                         : DAG.getUNDEF(VT.getVectorElementType());
5011
5012   if (V.getOpcode() == ISD::BUILD_VECTOR)
5013     return V.getOperand(Index);
5014
5015   return SDValue();
5016 }
5017
5018 /// Custom lower build_vector of v16i8.
5019 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5020                                        unsigned NumNonZero, unsigned NumZero,
5021                                        SelectionDAG &DAG,
5022                                        const X86Subtarget* Subtarget,
5023                                        const TargetLowering &TLI) {
5024   if (NumNonZero > 8)
5025     return SDValue();
5026
5027   SDLoc dl(Op);
5028   SDValue V;
5029   bool First = true;
5030
5031   // SSE4.1 - use PINSRB to insert each byte directly.
5032   if (Subtarget->hasSSE41()) {
5033     for (unsigned i = 0; i < 16; ++i) {
5034       bool isNonZero = (NonZeros & (1 << i)) != 0;
5035       if (isNonZero) {
5036         if (First) {
5037           if (NumZero)
5038             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5039           else
5040             V = DAG.getUNDEF(MVT::v16i8);
5041           First = false;
5042         }
5043         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5044                         MVT::v16i8, V, Op.getOperand(i),
5045                         DAG.getIntPtrConstant(i, dl));
5046       }
5047     }
5048
5049     return V;
5050   }
5051
5052   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5053   for (unsigned i = 0; i < 16; ++i) {
5054     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5055     if (ThisIsNonZero && First) {
5056       if (NumZero)
5057         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5058       else
5059         V = DAG.getUNDEF(MVT::v8i16);
5060       First = false;
5061     }
5062
5063     if ((i & 1) != 0) {
5064       SDValue ThisElt, LastElt;
5065       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5066       if (LastIsNonZero) {
5067         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5068                               MVT::i16, Op.getOperand(i-1));
5069       }
5070       if (ThisIsNonZero) {
5071         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5072         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5073                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
5074         if (LastIsNonZero)
5075           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5076       } else
5077         ThisElt = LastElt;
5078
5079       if (ThisElt.getNode())
5080         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5081                         DAG.getIntPtrConstant(i/2, dl));
5082     }
5083   }
5084
5085   return DAG.getBitcast(MVT::v16i8, V);
5086 }
5087
5088 /// Custom lower build_vector of v8i16.
5089 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5090                                      unsigned NumNonZero, unsigned NumZero,
5091                                      SelectionDAG &DAG,
5092                                      const X86Subtarget* Subtarget,
5093                                      const TargetLowering &TLI) {
5094   if (NumNonZero > 4)
5095     return SDValue();
5096
5097   SDLoc dl(Op);
5098   SDValue V;
5099   bool First = true;
5100   for (unsigned i = 0; i < 8; ++i) {
5101     bool isNonZero = (NonZeros & (1 << i)) != 0;
5102     if (isNonZero) {
5103       if (First) {
5104         if (NumZero)
5105           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5106         else
5107           V = DAG.getUNDEF(MVT::v8i16);
5108         First = false;
5109       }
5110       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5111                       MVT::v8i16, V, Op.getOperand(i),
5112                       DAG.getIntPtrConstant(i, dl));
5113     }
5114   }
5115
5116   return V;
5117 }
5118
5119 /// Custom lower build_vector of v4i32 or v4f32.
5120 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5121                                      const X86Subtarget *Subtarget,
5122                                      const TargetLowering &TLI) {
5123   // Find all zeroable elements.
5124   std::bitset<4> Zeroable;
5125   for (int i=0; i < 4; ++i) {
5126     SDValue Elt = Op->getOperand(i);
5127     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5128   }
5129   assert(Zeroable.size() - Zeroable.count() > 1 &&
5130          "We expect at least two non-zero elements!");
5131
5132   // We only know how to deal with build_vector nodes where elements are either
5133   // zeroable or extract_vector_elt with constant index.
5134   SDValue FirstNonZero;
5135   unsigned FirstNonZeroIdx;
5136   for (unsigned i=0; i < 4; ++i) {
5137     if (Zeroable[i])
5138       continue;
5139     SDValue Elt = Op->getOperand(i);
5140     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5141         !isa<ConstantSDNode>(Elt.getOperand(1)))
5142       return SDValue();
5143     // Make sure that this node is extracting from a 128-bit vector.
5144     MVT VT = Elt.getOperand(0).getSimpleValueType();
5145     if (!VT.is128BitVector())
5146       return SDValue();
5147     if (!FirstNonZero.getNode()) {
5148       FirstNonZero = Elt;
5149       FirstNonZeroIdx = i;
5150     }
5151   }
5152
5153   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5154   SDValue V1 = FirstNonZero.getOperand(0);
5155   MVT VT = V1.getSimpleValueType();
5156
5157   // See if this build_vector can be lowered as a blend with zero.
5158   SDValue Elt;
5159   unsigned EltMaskIdx, EltIdx;
5160   int Mask[4];
5161   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5162     if (Zeroable[EltIdx]) {
5163       // The zero vector will be on the right hand side.
5164       Mask[EltIdx] = EltIdx+4;
5165       continue;
5166     }
5167
5168     Elt = Op->getOperand(EltIdx);
5169     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5170     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5171     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5172       break;
5173     Mask[EltIdx] = EltIdx;
5174   }
5175
5176   if (EltIdx == 4) {
5177     // Let the shuffle legalizer deal with blend operations.
5178     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5179     if (V1.getSimpleValueType() != VT)
5180       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5181     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5182   }
5183
5184   // See if we can lower this build_vector to a INSERTPS.
5185   if (!Subtarget->hasSSE41())
5186     return SDValue();
5187
5188   SDValue V2 = Elt.getOperand(0);
5189   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5190     V1 = SDValue();
5191
5192   bool CanFold = true;
5193   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5194     if (Zeroable[i])
5195       continue;
5196
5197     SDValue Current = Op->getOperand(i);
5198     SDValue SrcVector = Current->getOperand(0);
5199     if (!V1.getNode())
5200       V1 = SrcVector;
5201     CanFold = SrcVector == V1 &&
5202       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5203   }
5204
5205   if (!CanFold)
5206     return SDValue();
5207
5208   assert(V1.getNode() && "Expected at least two non-zero elements!");
5209   if (V1.getSimpleValueType() != MVT::v4f32)
5210     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5211   if (V2.getSimpleValueType() != MVT::v4f32)
5212     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5213
5214   // Ok, we can emit an INSERTPS instruction.
5215   unsigned ZMask = Zeroable.to_ulong();
5216
5217   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5218   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5219   SDLoc DL(Op);
5220   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5221                                DAG.getIntPtrConstant(InsertPSMask, DL));
5222   return DAG.getBitcast(VT, Result);
5223 }
5224
5225 /// Return a vector logical shift node.
5226 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5227                          unsigned NumBits, SelectionDAG &DAG,
5228                          const TargetLowering &TLI, SDLoc dl) {
5229   assert(VT.is128BitVector() && "Unknown type for VShift");
5230   MVT ShVT = MVT::v2i64;
5231   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5232   SrcOp = DAG.getBitcast(ShVT, SrcOp);
5233   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5234   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5235   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5236   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5237 }
5238
5239 static SDValue
5240 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5241
5242   // Check if the scalar load can be widened into a vector load. And if
5243   // the address is "base + cst" see if the cst can be "absorbed" into
5244   // the shuffle mask.
5245   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5246     SDValue Ptr = LD->getBasePtr();
5247     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5248       return SDValue();
5249     EVT PVT = LD->getValueType(0);
5250     if (PVT != MVT::i32 && PVT != MVT::f32)
5251       return SDValue();
5252
5253     int FI = -1;
5254     int64_t Offset = 0;
5255     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5256       FI = FINode->getIndex();
5257       Offset = 0;
5258     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5259                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5260       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5261       Offset = Ptr.getConstantOperandVal(1);
5262       Ptr = Ptr.getOperand(0);
5263     } else {
5264       return SDValue();
5265     }
5266
5267     // FIXME: 256-bit vector instructions don't require a strict alignment,
5268     // improve this code to support it better.
5269     unsigned RequiredAlign = VT.getSizeInBits()/8;
5270     SDValue Chain = LD->getChain();
5271     // Make sure the stack object alignment is at least 16 or 32.
5272     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5273     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5274       if (MFI->isFixedObjectIndex(FI)) {
5275         // Can't change the alignment. FIXME: It's possible to compute
5276         // the exact stack offset and reference FI + adjust offset instead.
5277         // If someone *really* cares about this. That's the way to implement it.
5278         return SDValue();
5279       } else {
5280         MFI->setObjectAlignment(FI, RequiredAlign);
5281       }
5282     }
5283
5284     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5285     // Ptr + (Offset & ~15).
5286     if (Offset < 0)
5287       return SDValue();
5288     if ((Offset % RequiredAlign) & 3)
5289       return SDValue();
5290     int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5291     if (StartOffset) {
5292       SDLoc DL(Ptr);
5293       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5294                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5295     }
5296
5297     int EltNo = (Offset - StartOffset) >> 2;
5298     unsigned NumElems = VT.getVectorNumElements();
5299
5300     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5301     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5302                              LD->getPointerInfo().getWithOffset(StartOffset),
5303                              false, false, false, 0);
5304
5305     SmallVector<int, 8> Mask(NumElems, EltNo);
5306
5307     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5308   }
5309
5310   return SDValue();
5311 }
5312
5313 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5314 /// elements can be replaced by a single large load which has the same value as
5315 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5316 ///
5317 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5318 ///
5319 /// FIXME: we'd also like to handle the case where the last elements are zero
5320 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5321 /// There's even a handy isZeroNode for that purpose.
5322 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5323                                         SDLoc &DL, SelectionDAG &DAG,
5324                                         bool isAfterLegalize) {
5325   unsigned NumElems = Elts.size();
5326
5327   LoadSDNode *LDBase = nullptr;
5328   unsigned LastLoadedElt = -1U;
5329
5330   // For each element in the initializer, see if we've found a load or an undef.
5331   // If we don't find an initial load element, or later load elements are
5332   // non-consecutive, bail out.
5333   for (unsigned i = 0; i < NumElems; ++i) {
5334     SDValue Elt = Elts[i];
5335     // Look through a bitcast.
5336     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5337       Elt = Elt.getOperand(0);
5338     if (!Elt.getNode() ||
5339         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5340       return SDValue();
5341     if (!LDBase) {
5342       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5343         return SDValue();
5344       LDBase = cast<LoadSDNode>(Elt.getNode());
5345       LastLoadedElt = i;
5346       continue;
5347     }
5348     if (Elt.getOpcode() == ISD::UNDEF)
5349       continue;
5350
5351     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5352     EVT LdVT = Elt.getValueType();
5353     // Each loaded element must be the correct fractional portion of the
5354     // requested vector load.
5355     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5356       return SDValue();
5357     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5358       return SDValue();
5359     LastLoadedElt = i;
5360   }
5361
5362   // If we have found an entire vector of loads and undefs, then return a large
5363   // load of the entire vector width starting at the base pointer.  If we found
5364   // consecutive loads for the low half, generate a vzext_load node.
5365   if (LastLoadedElt == NumElems - 1) {
5366     assert(LDBase && "Did not find base load for merging consecutive loads");
5367     EVT EltVT = LDBase->getValueType(0);
5368     // Ensure that the input vector size for the merged loads matches the
5369     // cumulative size of the input elements.
5370     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5371       return SDValue();
5372
5373     if (isAfterLegalize &&
5374         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5375       return SDValue();
5376
5377     SDValue NewLd = SDValue();
5378
5379     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5380                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5381                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5382                         LDBase->getAlignment());
5383
5384     if (LDBase->hasAnyUseOfValue(1)) {
5385       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5386                                      SDValue(LDBase, 1),
5387                                      SDValue(NewLd.getNode(), 1));
5388       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5389       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5390                              SDValue(NewLd.getNode(), 1));
5391     }
5392
5393     return NewLd;
5394   }
5395
5396   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5397   //of a v4i32 / v4f32. It's probably worth generalizing.
5398   EVT EltVT = VT.getVectorElementType();
5399   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5400       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5401     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5402     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5403     SDValue ResNode =
5404         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5405                                 LDBase->getPointerInfo(),
5406                                 LDBase->getAlignment(),
5407                                 false/*isVolatile*/, true/*ReadMem*/,
5408                                 false/*WriteMem*/);
5409
5410     // Make sure the newly-created LOAD is in the same position as LDBase in
5411     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5412     // update uses of LDBase's output chain to use the TokenFactor.
5413     if (LDBase->hasAnyUseOfValue(1)) {
5414       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5415                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5416       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5417       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5418                              SDValue(ResNode.getNode(), 1));
5419     }
5420
5421     return DAG.getBitcast(VT, ResNode);
5422   }
5423   return SDValue();
5424 }
5425
5426 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5427 /// to generate a splat value for the following cases:
5428 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5429 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5430 /// a scalar load, or a constant.
5431 /// The VBROADCAST node is returned when a pattern is found,
5432 /// or SDValue() otherwise.
5433 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5434                                     SelectionDAG &DAG) {
5435   // VBROADCAST requires AVX.
5436   // TODO: Splats could be generated for non-AVX CPUs using SSE
5437   // instructions, but there's less potential gain for only 128-bit vectors.
5438   if (!Subtarget->hasAVX())
5439     return SDValue();
5440
5441   MVT VT = Op.getSimpleValueType();
5442   SDLoc dl(Op);
5443
5444   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5445          "Unsupported vector type for broadcast.");
5446
5447   SDValue Ld;
5448   bool ConstSplatVal;
5449
5450   switch (Op.getOpcode()) {
5451     default:
5452       // Unknown pattern found.
5453       return SDValue();
5454
5455     case ISD::BUILD_VECTOR: {
5456       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5457       BitVector UndefElements;
5458       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5459
5460       // We need a splat of a single value to use broadcast, and it doesn't
5461       // make any sense if the value is only in one element of the vector.
5462       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5463         return SDValue();
5464
5465       Ld = Splat;
5466       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5467                        Ld.getOpcode() == ISD::ConstantFP);
5468
5469       // Make sure that all of the users of a non-constant load are from the
5470       // BUILD_VECTOR node.
5471       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5472         return SDValue();
5473       break;
5474     }
5475
5476     case ISD::VECTOR_SHUFFLE: {
5477       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5478
5479       // Shuffles must have a splat mask where the first element is
5480       // broadcasted.
5481       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5482         return SDValue();
5483
5484       SDValue Sc = Op.getOperand(0);
5485       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5486           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5487
5488         if (!Subtarget->hasInt256())
5489           return SDValue();
5490
5491         // Use the register form of the broadcast instruction available on AVX2.
5492         if (VT.getSizeInBits() >= 256)
5493           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5494         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5495       }
5496
5497       Ld = Sc.getOperand(0);
5498       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5499                        Ld.getOpcode() == ISD::ConstantFP);
5500
5501       // The scalar_to_vector node and the suspected
5502       // load node must have exactly one user.
5503       // Constants may have multiple users.
5504
5505       // AVX-512 has register version of the broadcast
5506       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5507         Ld.getValueType().getSizeInBits() >= 32;
5508       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5509           !hasRegVer))
5510         return SDValue();
5511       break;
5512     }
5513   }
5514
5515   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5516   bool IsGE256 = (VT.getSizeInBits() >= 256);
5517
5518   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5519   // instruction to save 8 or more bytes of constant pool data.
5520   // TODO: If multiple splats are generated to load the same constant,
5521   // it may be detrimental to overall size. There needs to be a way to detect
5522   // that condition to know if this is truly a size win.
5523   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5524
5525   // Handle broadcasting a single constant scalar from the constant pool
5526   // into a vector.
5527   // On Sandybridge (no AVX2), it is still better to load a constant vector
5528   // from the constant pool and not to broadcast it from a scalar.
5529   // But override that restriction when optimizing for size.
5530   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5531   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5532     EVT CVT = Ld.getValueType();
5533     assert(!CVT.isVector() && "Must not broadcast a vector type");
5534
5535     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5536     // For size optimization, also splat v2f64 and v2i64, and for size opt
5537     // with AVX2, also splat i8 and i16.
5538     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5539     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5540         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5541       const Constant *C = nullptr;
5542       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5543         C = CI->getConstantIntValue();
5544       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5545         C = CF->getConstantFPValue();
5546
5547       assert(C && "Invalid constant type");
5548
5549       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5550       SDValue CP =
5551           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5552       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5553       Ld = DAG.getLoad(
5554           CVT, dl, DAG.getEntryNode(), CP,
5555           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5556           false, false, Alignment);
5557
5558       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5559     }
5560   }
5561
5562   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5563
5564   // Handle AVX2 in-register broadcasts.
5565   if (!IsLoad && Subtarget->hasInt256() &&
5566       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5567     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5568
5569   // The scalar source must be a normal load.
5570   if (!IsLoad)
5571     return SDValue();
5572
5573   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5574       (Subtarget->hasVLX() && ScalarSize == 64))
5575     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5576
5577   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5578   // double since there is no vbroadcastsd xmm
5579   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5580     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5581       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5582   }
5583
5584   // Unsupported broadcast.
5585   return SDValue();
5586 }
5587
5588 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5589 /// underlying vector and index.
5590 ///
5591 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5592 /// index.
5593 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5594                                          SDValue ExtIdx) {
5595   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5596   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5597     return Idx;
5598
5599   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5600   // lowered this:
5601   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5602   // to:
5603   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5604   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5605   //                           undef)
5606   //                       Constant<0>)
5607   // In this case the vector is the extract_subvector expression and the index
5608   // is 2, as specified by the shuffle.
5609   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5610   SDValue ShuffleVec = SVOp->getOperand(0);
5611   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5612   assert(ShuffleVecVT.getVectorElementType() ==
5613          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5614
5615   int ShuffleIdx = SVOp->getMaskElt(Idx);
5616   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5617     ExtractedFromVec = ShuffleVec;
5618     return ShuffleIdx;
5619   }
5620   return Idx;
5621 }
5622
5623 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5624   MVT VT = Op.getSimpleValueType();
5625
5626   // Skip if insert_vec_elt is not supported.
5627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5628   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5629     return SDValue();
5630
5631   SDLoc DL(Op);
5632   unsigned NumElems = Op.getNumOperands();
5633
5634   SDValue VecIn1;
5635   SDValue VecIn2;
5636   SmallVector<unsigned, 4> InsertIndices;
5637   SmallVector<int, 8> Mask(NumElems, -1);
5638
5639   for (unsigned i = 0; i != NumElems; ++i) {
5640     unsigned Opc = Op.getOperand(i).getOpcode();
5641
5642     if (Opc == ISD::UNDEF)
5643       continue;
5644
5645     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5646       // Quit if more than 1 elements need inserting.
5647       if (InsertIndices.size() > 1)
5648         return SDValue();
5649
5650       InsertIndices.push_back(i);
5651       continue;
5652     }
5653
5654     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5655     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5656     // Quit if non-constant index.
5657     if (!isa<ConstantSDNode>(ExtIdx))
5658       return SDValue();
5659     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5660
5661     // Quit if extracted from vector of different type.
5662     if (ExtractedFromVec.getValueType() != VT)
5663       return SDValue();
5664
5665     if (!VecIn1.getNode())
5666       VecIn1 = ExtractedFromVec;
5667     else if (VecIn1 != ExtractedFromVec) {
5668       if (!VecIn2.getNode())
5669         VecIn2 = ExtractedFromVec;
5670       else if (VecIn2 != ExtractedFromVec)
5671         // Quit if more than 2 vectors to shuffle
5672         return SDValue();
5673     }
5674
5675     if (ExtractedFromVec == VecIn1)
5676       Mask[i] = Idx;
5677     else if (ExtractedFromVec == VecIn2)
5678       Mask[i] = Idx + NumElems;
5679   }
5680
5681   if (!VecIn1.getNode())
5682     return SDValue();
5683
5684   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5685   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5686   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5687     unsigned Idx = InsertIndices[i];
5688     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5689                      DAG.getIntPtrConstant(Idx, DL));
5690   }
5691
5692   return NV;
5693 }
5694
5695 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5696   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5697          Op.getScalarValueSizeInBits() == 1 &&
5698          "Can not convert non-constant vector");
5699   uint64_t Immediate = 0;
5700   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5701     SDValue In = Op.getOperand(idx);
5702     if (In.getOpcode() != ISD::UNDEF)
5703       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5704   }
5705   SDLoc dl(Op);
5706   MVT VT =
5707    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5708   return DAG.getConstant(Immediate, dl, VT);
5709 }
5710 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5711 SDValue
5712 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5713
5714   MVT VT = Op.getSimpleValueType();
5715   assert((VT.getVectorElementType() == MVT::i1) &&
5716          "Unexpected type in LowerBUILD_VECTORvXi1!");
5717
5718   SDLoc dl(Op);
5719   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5720     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5721     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5722     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5723   }
5724
5725   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5726     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5727     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5728     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5729   }
5730
5731   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5732     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5733     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5734       return DAG.getBitcast(VT, Imm);
5735     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5736     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5737                         DAG.getIntPtrConstant(0, dl));
5738   }
5739
5740   // Vector has one or more non-const elements
5741   uint64_t Immediate = 0;
5742   SmallVector<unsigned, 16> NonConstIdx;
5743   bool IsSplat = true;
5744   bool HasConstElts = false;
5745   int SplatIdx = -1;
5746   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5747     SDValue In = Op.getOperand(idx);
5748     if (In.getOpcode() == ISD::UNDEF)
5749       continue;
5750     if (!isa<ConstantSDNode>(In))
5751       NonConstIdx.push_back(idx);
5752     else {
5753       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5754       HasConstElts = true;
5755     }
5756     if (SplatIdx == -1)
5757       SplatIdx = idx;
5758     else if (In != Op.getOperand(SplatIdx))
5759       IsSplat = false;
5760   }
5761
5762   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5763   if (IsSplat)
5764     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5765                        DAG.getConstant(1, dl, VT),
5766                        DAG.getConstant(0, dl, VT));
5767
5768   // insert elements one by one
5769   SDValue DstVec;
5770   SDValue Imm;
5771   if (Immediate) {
5772     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5773     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5774   }
5775   else if (HasConstElts)
5776     Imm = DAG.getConstant(0, dl, VT);
5777   else
5778     Imm = DAG.getUNDEF(VT);
5779   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5780     DstVec = DAG.getBitcast(VT, Imm);
5781   else {
5782     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5783     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5784                          DAG.getIntPtrConstant(0, dl));
5785   }
5786
5787   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5788     unsigned InsertIdx = NonConstIdx[i];
5789     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5790                          Op.getOperand(InsertIdx),
5791                          DAG.getIntPtrConstant(InsertIdx, dl));
5792   }
5793   return DstVec;
5794 }
5795
5796 /// \brief Return true if \p N implements a horizontal binop and return the
5797 /// operands for the horizontal binop into V0 and V1.
5798 ///
5799 /// This is a helper function of LowerToHorizontalOp().
5800 /// This function checks that the build_vector \p N in input implements a
5801 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5802 /// operation to match.
5803 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5804 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5805 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5806 /// arithmetic sub.
5807 ///
5808 /// This function only analyzes elements of \p N whose indices are
5809 /// in range [BaseIdx, LastIdx).
5810 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5811                               SelectionDAG &DAG,
5812                               unsigned BaseIdx, unsigned LastIdx,
5813                               SDValue &V0, SDValue &V1) {
5814   EVT VT = N->getValueType(0);
5815
5816   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5817   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5818          "Invalid Vector in input!");
5819
5820   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5821   bool CanFold = true;
5822   unsigned ExpectedVExtractIdx = BaseIdx;
5823   unsigned NumElts = LastIdx - BaseIdx;
5824   V0 = DAG.getUNDEF(VT);
5825   V1 = DAG.getUNDEF(VT);
5826
5827   // Check if N implements a horizontal binop.
5828   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5829     SDValue Op = N->getOperand(i + BaseIdx);
5830
5831     // Skip UNDEFs.
5832     if (Op->getOpcode() == ISD::UNDEF) {
5833       // Update the expected vector extract index.
5834       if (i * 2 == NumElts)
5835         ExpectedVExtractIdx = BaseIdx;
5836       ExpectedVExtractIdx += 2;
5837       continue;
5838     }
5839
5840     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5841
5842     if (!CanFold)
5843       break;
5844
5845     SDValue Op0 = Op.getOperand(0);
5846     SDValue Op1 = Op.getOperand(1);
5847
5848     // Try to match the following pattern:
5849     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5850     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5851         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5852         Op0.getOperand(0) == Op1.getOperand(0) &&
5853         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5854         isa<ConstantSDNode>(Op1.getOperand(1)));
5855     if (!CanFold)
5856       break;
5857
5858     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5859     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5860
5861     if (i * 2 < NumElts) {
5862       if (V0.getOpcode() == ISD::UNDEF) {
5863         V0 = Op0.getOperand(0);
5864         if (V0.getValueType() != VT)
5865           return false;
5866       }
5867     } else {
5868       if (V1.getOpcode() == ISD::UNDEF) {
5869         V1 = Op0.getOperand(0);
5870         if (V1.getValueType() != VT)
5871           return false;
5872       }
5873       if (i * 2 == NumElts)
5874         ExpectedVExtractIdx = BaseIdx;
5875     }
5876
5877     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5878     if (I0 == ExpectedVExtractIdx)
5879       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5880     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5881       // Try to match the following dag sequence:
5882       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5883       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5884     } else
5885       CanFold = false;
5886
5887     ExpectedVExtractIdx += 2;
5888   }
5889
5890   return CanFold;
5891 }
5892
5893 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5894 /// a concat_vector.
5895 ///
5896 /// This is a helper function of LowerToHorizontalOp().
5897 /// This function expects two 256-bit vectors called V0 and V1.
5898 /// At first, each vector is split into two separate 128-bit vectors.
5899 /// Then, the resulting 128-bit vectors are used to implement two
5900 /// horizontal binary operations.
5901 ///
5902 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5903 ///
5904 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5905 /// the two new horizontal binop.
5906 /// When Mode is set, the first horizontal binop dag node would take as input
5907 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5908 /// horizontal binop dag node would take as input the lower 128-bit of V1
5909 /// and the upper 128-bit of V1.
5910 ///   Example:
5911 ///     HADD V0_LO, V0_HI
5912 ///     HADD V1_LO, V1_HI
5913 ///
5914 /// Otherwise, the first horizontal binop dag node takes as input the lower
5915 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5916 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5917 ///   Example:
5918 ///     HADD V0_LO, V1_LO
5919 ///     HADD V0_HI, V1_HI
5920 ///
5921 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5922 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5923 /// the upper 128-bits of the result.
5924 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5925                                      SDLoc DL, SelectionDAG &DAG,
5926                                      unsigned X86Opcode, bool Mode,
5927                                      bool isUndefLO, bool isUndefHI) {
5928   EVT VT = V0.getValueType();
5929   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5930          "Invalid nodes in input!");
5931
5932   unsigned NumElts = VT.getVectorNumElements();
5933   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5934   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5935   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5936   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5937   EVT NewVT = V0_LO.getValueType();
5938
5939   SDValue LO = DAG.getUNDEF(NewVT);
5940   SDValue HI = DAG.getUNDEF(NewVT);
5941
5942   if (Mode) {
5943     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5944     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5945       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5946     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5947       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5948   } else {
5949     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5950     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5951                        V1_LO->getOpcode() != ISD::UNDEF))
5952       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5953
5954     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5955                        V1_HI->getOpcode() != ISD::UNDEF))
5956       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5957   }
5958
5959   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5960 }
5961
5962 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5963 /// node.
5964 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5965                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5966   MVT VT = BV->getSimpleValueType(0);
5967   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5968       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5969     return SDValue();
5970
5971   SDLoc DL(BV);
5972   unsigned NumElts = VT.getVectorNumElements();
5973   SDValue InVec0 = DAG.getUNDEF(VT);
5974   SDValue InVec1 = DAG.getUNDEF(VT);
5975
5976   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5977           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5978
5979   // Odd-numbered elements in the input build vector are obtained from
5980   // adding two integer/float elements.
5981   // Even-numbered elements in the input build vector are obtained from
5982   // subtracting two integer/float elements.
5983   unsigned ExpectedOpcode = ISD::FSUB;
5984   unsigned NextExpectedOpcode = ISD::FADD;
5985   bool AddFound = false;
5986   bool SubFound = false;
5987
5988   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5989     SDValue Op = BV->getOperand(i);
5990
5991     // Skip 'undef' values.
5992     unsigned Opcode = Op.getOpcode();
5993     if (Opcode == ISD::UNDEF) {
5994       std::swap(ExpectedOpcode, NextExpectedOpcode);
5995       continue;
5996     }
5997
5998     // Early exit if we found an unexpected opcode.
5999     if (Opcode != ExpectedOpcode)
6000       return SDValue();
6001
6002     SDValue Op0 = Op.getOperand(0);
6003     SDValue Op1 = Op.getOperand(1);
6004
6005     // Try to match the following pattern:
6006     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6007     // Early exit if we cannot match that sequence.
6008     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6009         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6010         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6011         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6012         Op0.getOperand(1) != Op1.getOperand(1))
6013       return SDValue();
6014
6015     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6016     if (I0 != i)
6017       return SDValue();
6018
6019     // We found a valid add/sub node. Update the information accordingly.
6020     if (i & 1)
6021       AddFound = true;
6022     else
6023       SubFound = true;
6024
6025     // Update InVec0 and InVec1.
6026     if (InVec0.getOpcode() == ISD::UNDEF) {
6027       InVec0 = Op0.getOperand(0);
6028       if (InVec0.getSimpleValueType() != VT)
6029         return SDValue();
6030     }
6031     if (InVec1.getOpcode() == ISD::UNDEF) {
6032       InVec1 = Op1.getOperand(0);
6033       if (InVec1.getSimpleValueType() != VT)
6034         return SDValue();
6035     }
6036
6037     // Make sure that operands in input to each add/sub node always
6038     // come from a same pair of vectors.
6039     if (InVec0 != Op0.getOperand(0)) {
6040       if (ExpectedOpcode == ISD::FSUB)
6041         return SDValue();
6042
6043       // FADD is commutable. Try to commute the operands
6044       // and then test again.
6045       std::swap(Op0, Op1);
6046       if (InVec0 != Op0.getOperand(0))
6047         return SDValue();
6048     }
6049
6050     if (InVec1 != Op1.getOperand(0))
6051       return SDValue();
6052
6053     // Update the pair of expected opcodes.
6054     std::swap(ExpectedOpcode, NextExpectedOpcode);
6055   }
6056
6057   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6058   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6059       InVec1.getOpcode() != ISD::UNDEF)
6060     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6061
6062   return SDValue();
6063 }
6064
6065 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6066 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6067                                    const X86Subtarget *Subtarget,
6068                                    SelectionDAG &DAG) {
6069   MVT VT = BV->getSimpleValueType(0);
6070   unsigned NumElts = VT.getVectorNumElements();
6071   unsigned NumUndefsLO = 0;
6072   unsigned NumUndefsHI = 0;
6073   unsigned Half = NumElts/2;
6074
6075   // Count the number of UNDEF operands in the build_vector in input.
6076   for (unsigned i = 0, e = Half; i != e; ++i)
6077     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6078       NumUndefsLO++;
6079
6080   for (unsigned i = Half, e = NumElts; i != e; ++i)
6081     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6082       NumUndefsHI++;
6083
6084   // Early exit if this is either a build_vector of all UNDEFs or all the
6085   // operands but one are UNDEF.
6086   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6087     return SDValue();
6088
6089   SDLoc DL(BV);
6090   SDValue InVec0, InVec1;
6091   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6092     // Try to match an SSE3 float HADD/HSUB.
6093     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6094       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6095
6096     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6097       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6098   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6099     // Try to match an SSSE3 integer HADD/HSUB.
6100     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6101       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6102
6103     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6104       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6105   }
6106
6107   if (!Subtarget->hasAVX())
6108     return SDValue();
6109
6110   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6111     // Try to match an AVX horizontal add/sub of packed single/double
6112     // precision floating point values from 256-bit vectors.
6113     SDValue InVec2, InVec3;
6114     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6115         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6116         ((InVec0.getOpcode() == ISD::UNDEF ||
6117           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6118         ((InVec1.getOpcode() == ISD::UNDEF ||
6119           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6120       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6121
6122     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6123         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6124         ((InVec0.getOpcode() == ISD::UNDEF ||
6125           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6126         ((InVec1.getOpcode() == ISD::UNDEF ||
6127           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6128       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6129   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6130     // Try to match an AVX2 horizontal add/sub of signed integers.
6131     SDValue InVec2, InVec3;
6132     unsigned X86Opcode;
6133     bool CanFold = true;
6134
6135     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6136         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6137         ((InVec0.getOpcode() == ISD::UNDEF ||
6138           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6139         ((InVec1.getOpcode() == ISD::UNDEF ||
6140           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6141       X86Opcode = X86ISD::HADD;
6142     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6143         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6144         ((InVec0.getOpcode() == ISD::UNDEF ||
6145           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6146         ((InVec1.getOpcode() == ISD::UNDEF ||
6147           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6148       X86Opcode = X86ISD::HSUB;
6149     else
6150       CanFold = false;
6151
6152     if (CanFold) {
6153       // Fold this build_vector into a single horizontal add/sub.
6154       // Do this only if the target has AVX2.
6155       if (Subtarget->hasAVX2())
6156         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6157
6158       // Do not try to expand this build_vector into a pair of horizontal
6159       // add/sub if we can emit a pair of scalar add/sub.
6160       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6161         return SDValue();
6162
6163       // Convert this build_vector into a pair of horizontal binop followed by
6164       // a concat vector.
6165       bool isUndefLO = NumUndefsLO == Half;
6166       bool isUndefHI = NumUndefsHI == Half;
6167       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6168                                    isUndefLO, isUndefHI);
6169     }
6170   }
6171
6172   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6173        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6174     unsigned X86Opcode;
6175     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6176       X86Opcode = X86ISD::HADD;
6177     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6178       X86Opcode = X86ISD::HSUB;
6179     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6180       X86Opcode = X86ISD::FHADD;
6181     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6182       X86Opcode = X86ISD::FHSUB;
6183     else
6184       return SDValue();
6185
6186     // Don't try to expand this build_vector into a pair of horizontal add/sub
6187     // if we can simply emit a pair of scalar add/sub.
6188     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6189       return SDValue();
6190
6191     // Convert this build_vector into two horizontal add/sub followed by
6192     // a concat vector.
6193     bool isUndefLO = NumUndefsLO == Half;
6194     bool isUndefHI = NumUndefsHI == Half;
6195     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6196                                  isUndefLO, isUndefHI);
6197   }
6198
6199   return SDValue();
6200 }
6201
6202 SDValue
6203 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6204   SDLoc dl(Op);
6205
6206   MVT VT = Op.getSimpleValueType();
6207   MVT ExtVT = VT.getVectorElementType();
6208   unsigned NumElems = Op.getNumOperands();
6209
6210   // Generate vectors for predicate vectors.
6211   if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6212     return LowerBUILD_VECTORvXi1(Op, DAG);
6213
6214   // Vectors containing all zeros can be matched by pxor and xorps later
6215   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6216     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6217     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6218     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6219       return Op;
6220
6221     return getZeroVector(VT, Subtarget, DAG, dl);
6222   }
6223
6224   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6225   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6226   // vpcmpeqd on 256-bit vectors.
6227   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6228     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6229       return Op;
6230
6231     if (!VT.is512BitVector())
6232       return getOnesVector(VT, Subtarget, DAG, dl);
6233   }
6234
6235   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6236   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6237     return AddSub;
6238   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6239     return HorizontalOp;
6240   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6241     return Broadcast;
6242
6243   unsigned EVTBits = ExtVT.getSizeInBits();
6244
6245   unsigned NumZero  = 0;
6246   unsigned NumNonZero = 0;
6247   uint64_t NonZeros = 0;
6248   bool IsAllConstants = true;
6249   SmallSet<SDValue, 8> Values;
6250   for (unsigned i = 0; i < NumElems; ++i) {
6251     SDValue Elt = Op.getOperand(i);
6252     if (Elt.getOpcode() == ISD::UNDEF)
6253       continue;
6254     Values.insert(Elt);
6255     if (Elt.getOpcode() != ISD::Constant &&
6256         Elt.getOpcode() != ISD::ConstantFP)
6257       IsAllConstants = false;
6258     if (X86::isZeroNode(Elt))
6259       NumZero++;
6260     else {
6261       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6262       NonZeros |= ((uint64_t)1 << i);
6263       NumNonZero++;
6264     }
6265   }
6266
6267   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6268   if (NumNonZero == 0)
6269     return DAG.getUNDEF(VT);
6270
6271   // Special case for single non-zero, non-undef, element.
6272   if (NumNonZero == 1) {
6273     unsigned Idx = countTrailingZeros(NonZeros);
6274     SDValue Item = Op.getOperand(Idx);
6275
6276     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6277     // the value are obviously zero, truncate the value to i32 and do the
6278     // insertion that way.  Only do this if the value is non-constant or if the
6279     // value is a constant being inserted into element 0.  It is cheaper to do
6280     // a constant pool load than it is to do a movd + shuffle.
6281     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6282         (!IsAllConstants || Idx == 0)) {
6283       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6284         // Handle SSE only.
6285         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6286         MVT VecVT = MVT::v4i32;
6287
6288         // Truncate the value (which may itself be a constant) to i32, and
6289         // convert it to a vector with movd (S2V+shuffle to zero extend).
6290         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6291         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6292         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6293                                       Item, Idx * 2, true, Subtarget, DAG));
6294       }
6295     }
6296
6297     // If we have a constant or non-constant insertion into the low element of
6298     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6299     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6300     // depending on what the source datatype is.
6301     if (Idx == 0) {
6302       if (NumZero == 0)
6303         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6304
6305       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6306           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6307         if (VT.is512BitVector()) {
6308           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6309           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6310                              Item, DAG.getIntPtrConstant(0, dl));
6311         }
6312         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6313                "Expected an SSE value type!");
6314         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6315         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6316         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6317       }
6318
6319       // We can't directly insert an i8 or i16 into a vector, so zero extend
6320       // it to i32 first.
6321       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6322         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6323         if (VT.is256BitVector()) {
6324           if (Subtarget->hasAVX()) {
6325             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6326             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6327           } else {
6328             // Without AVX, we need to extend to a 128-bit vector and then
6329             // insert into the 256-bit vector.
6330             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6331             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6332             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6333           }
6334         } else {
6335           assert(VT.is128BitVector() && "Expected an SSE value type!");
6336           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6337           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6338         }
6339         return DAG.getBitcast(VT, Item);
6340       }
6341     }
6342
6343     // Is it a vector logical left shift?
6344     if (NumElems == 2 && Idx == 1 &&
6345         X86::isZeroNode(Op.getOperand(0)) &&
6346         !X86::isZeroNode(Op.getOperand(1))) {
6347       unsigned NumBits = VT.getSizeInBits();
6348       return getVShift(true, VT,
6349                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6350                                    VT, Op.getOperand(1)),
6351                        NumBits/2, DAG, *this, dl);
6352     }
6353
6354     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6355       return SDValue();
6356
6357     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6358     // is a non-constant being inserted into an element other than the low one,
6359     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6360     // movd/movss) to move this into the low element, then shuffle it into
6361     // place.
6362     if (EVTBits == 32) {
6363       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6364       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6365     }
6366   }
6367
6368   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6369   if (Values.size() == 1) {
6370     if (EVTBits == 32) {
6371       // Instead of a shuffle like this:
6372       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6373       // Check if it's possible to issue this instead.
6374       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6375       unsigned Idx = countTrailingZeros(NonZeros);
6376       SDValue Item = Op.getOperand(Idx);
6377       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6378         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6379     }
6380     return SDValue();
6381   }
6382
6383   // A vector full of immediates; various special cases are already
6384   // handled, so this is best done with a single constant-pool load.
6385   if (IsAllConstants)
6386     return SDValue();
6387
6388   // For AVX-length vectors, see if we can use a vector load to get all of the
6389   // elements, otherwise build the individual 128-bit pieces and use
6390   // shuffles to put them in place.
6391   if (VT.is256BitVector() || VT.is512BitVector()) {
6392     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6393
6394     // Check for a build vector of consecutive loads.
6395     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6396       return LD;
6397
6398     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6399
6400     // Build both the lower and upper subvector.
6401     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6402                                 makeArrayRef(&V[0], NumElems/2));
6403     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6404                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6405
6406     // Recreate the wider vector with the lower and upper part.
6407     if (VT.is256BitVector())
6408       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6409     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6410   }
6411
6412   // Let legalizer expand 2-wide build_vectors.
6413   if (EVTBits == 64) {
6414     if (NumNonZero == 1) {
6415       // One half is zero or undef.
6416       unsigned Idx = countTrailingZeros(NonZeros);
6417       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6418                                Op.getOperand(Idx));
6419       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6420     }
6421     return SDValue();
6422   }
6423
6424   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6425   if (EVTBits == 8 && NumElems == 16)
6426     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6427                                           DAG, Subtarget, *this))
6428       return V;
6429
6430   if (EVTBits == 16 && NumElems == 8)
6431     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6432                                           DAG, Subtarget, *this))
6433       return V;
6434
6435   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6436   if (EVTBits == 32 && NumElems == 4)
6437     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6438       return V;
6439
6440   // If element VT is == 32 bits, turn it into a number of shuffles.
6441   SmallVector<SDValue, 8> V(NumElems);
6442   if (NumElems == 4 && NumZero > 0) {
6443     for (unsigned i = 0; i < 4; ++i) {
6444       bool isZero = !(NonZeros & (1 << i));
6445       if (isZero)
6446         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6447       else
6448         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6449     }
6450
6451     for (unsigned i = 0; i < 2; ++i) {
6452       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6453         default: break;
6454         case 0:
6455           V[i] = V[i*2];  // Must be a zero vector.
6456           break;
6457         case 1:
6458           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6459           break;
6460         case 2:
6461           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6462           break;
6463         case 3:
6464           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6465           break;
6466       }
6467     }
6468
6469     bool Reverse1 = (NonZeros & 0x3) == 2;
6470     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6471     int MaskVec[] = {
6472       Reverse1 ? 1 : 0,
6473       Reverse1 ? 0 : 1,
6474       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6475       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6476     };
6477     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6478   }
6479
6480   if (Values.size() > 1 && VT.is128BitVector()) {
6481     // Check for a build vector of consecutive loads.
6482     for (unsigned i = 0; i < NumElems; ++i)
6483       V[i] = Op.getOperand(i);
6484
6485     // Check for elements which are consecutive loads.
6486     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6487       return LD;
6488
6489     // Check for a build vector from mostly shuffle plus few inserting.
6490     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6491       return Sh;
6492
6493     // For SSE 4.1, use insertps to put the high elements into the low element.
6494     if (Subtarget->hasSSE41()) {
6495       SDValue Result;
6496       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6497         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6498       else
6499         Result = DAG.getUNDEF(VT);
6500
6501       for (unsigned i = 1; i < NumElems; ++i) {
6502         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6503         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6504                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6505       }
6506       return Result;
6507     }
6508
6509     // Otherwise, expand into a number of unpckl*, start by extending each of
6510     // our (non-undef) elements to the full vector width with the element in the
6511     // bottom slot of the vector (which generates no code for SSE).
6512     for (unsigned i = 0; i < NumElems; ++i) {
6513       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6514         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6515       else
6516         V[i] = DAG.getUNDEF(VT);
6517     }
6518
6519     // Next, we iteratively mix elements, e.g. for v4f32:
6520     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6521     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6522     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6523     unsigned EltStride = NumElems >> 1;
6524     while (EltStride != 0) {
6525       for (unsigned i = 0; i < EltStride; ++i) {
6526         // If V[i+EltStride] is undef and this is the first round of mixing,
6527         // then it is safe to just drop this shuffle: V[i] is already in the
6528         // right place, the one element (since it's the first round) being
6529         // inserted as undef can be dropped.  This isn't safe for successive
6530         // rounds because they will permute elements within both vectors.
6531         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6532             EltStride == NumElems/2)
6533           continue;
6534
6535         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6536       }
6537       EltStride >>= 1;
6538     }
6539     return V[0];
6540   }
6541   return SDValue();
6542 }
6543
6544 // 256-bit AVX can use the vinsertf128 instruction
6545 // to create 256-bit vectors from two other 128-bit ones.
6546 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6547   SDLoc dl(Op);
6548   MVT ResVT = Op.getSimpleValueType();
6549
6550   assert((ResVT.is256BitVector() ||
6551           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6552
6553   SDValue V1 = Op.getOperand(0);
6554   SDValue V2 = Op.getOperand(1);
6555   unsigned NumElems = ResVT.getVectorNumElements();
6556   if (ResVT.is256BitVector())
6557     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6558
6559   if (Op.getNumOperands() == 4) {
6560     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6561                                   ResVT.getVectorNumElements()/2);
6562     SDValue V3 = Op.getOperand(2);
6563     SDValue V4 = Op.getOperand(3);
6564     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6565       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6566   }
6567   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6568 }
6569
6570 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6571                                        const X86Subtarget *Subtarget,
6572                                        SelectionDAG & DAG) {
6573   SDLoc dl(Op);
6574   MVT ResVT = Op.getSimpleValueType();
6575   unsigned NumOfOperands = Op.getNumOperands();
6576
6577   assert(isPowerOf2_32(NumOfOperands) &&
6578          "Unexpected number of operands in CONCAT_VECTORS");
6579
6580   SDValue Undef = DAG.getUNDEF(ResVT);
6581   if (NumOfOperands > 2) {
6582     // Specialize the cases when all, or all but one, of the operands are undef.
6583     unsigned NumOfDefinedOps = 0;
6584     unsigned OpIdx = 0;
6585     for (unsigned i = 0; i < NumOfOperands; i++)
6586       if (!Op.getOperand(i).isUndef()) {
6587         NumOfDefinedOps++;
6588         OpIdx = i;
6589       }
6590     if (NumOfDefinedOps == 0)
6591       return Undef;
6592     if (NumOfDefinedOps == 1) {
6593       unsigned SubVecNumElts =
6594         Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6595       SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6596       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6597                          Op.getOperand(OpIdx), IdxVal);
6598     }
6599
6600     MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6601                                   ResVT.getVectorNumElements()/2);
6602     SmallVector<SDValue, 2> Ops;
6603     for (unsigned i = 0; i < NumOfOperands/2; i++)
6604       Ops.push_back(Op.getOperand(i));
6605     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6606     Ops.clear();
6607     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6608       Ops.push_back(Op.getOperand(i));
6609     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6610     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6611   }
6612
6613   // 2 operands
6614   SDValue V1 = Op.getOperand(0);
6615   SDValue V2 = Op.getOperand(1);
6616   unsigned NumElems = ResVT.getVectorNumElements();
6617   assert(V1.getValueType() == V2.getValueType() &&
6618          V1.getValueType().getVectorNumElements() == NumElems/2 &&
6619          "Unexpected operands in CONCAT_VECTORS");
6620
6621   if (ResVT.getSizeInBits() >= 16)
6622     return Op; // The operation is legal with KUNPCK
6623
6624   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6625   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6626   SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6627   if (IsZeroV1 && IsZeroV2)
6628     return ZeroVec;
6629
6630   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6631   if (V2.isUndef())
6632     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6633   if (IsZeroV2)
6634     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6635
6636   SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6637   if (V1.isUndef())
6638     V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6639
6640   if (IsZeroV1)
6641     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6642
6643   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6644   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6645 }
6646
6647 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6648                                    const X86Subtarget *Subtarget,
6649                                    SelectionDAG &DAG) {
6650   MVT VT = Op.getSimpleValueType();
6651   if (VT.getVectorElementType() == MVT::i1)
6652     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6653
6654   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6655          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6656           Op.getNumOperands() == 4)));
6657
6658   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6659   // from two other 128-bit ones.
6660
6661   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6662   return LowerAVXCONCAT_VECTORS(Op, DAG);
6663 }
6664
6665 //===----------------------------------------------------------------------===//
6666 // Vector shuffle lowering
6667 //
6668 // This is an experimental code path for lowering vector shuffles on x86. It is
6669 // designed to handle arbitrary vector shuffles and blends, gracefully
6670 // degrading performance as necessary. It works hard to recognize idiomatic
6671 // shuffles and lower them to optimal instruction patterns without leaving
6672 // a framework that allows reasonably efficient handling of all vector shuffle
6673 // patterns.
6674 //===----------------------------------------------------------------------===//
6675
6676 /// \brief Tiny helper function to identify a no-op mask.
6677 ///
6678 /// This is a somewhat boring predicate function. It checks whether the mask
6679 /// array input, which is assumed to be a single-input shuffle mask of the kind
6680 /// used by the X86 shuffle instructions (not a fully general
6681 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6682 /// in-place shuffle are 'no-op's.
6683 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6684   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6685     if (Mask[i] != -1 && Mask[i] != i)
6686       return false;
6687   return true;
6688 }
6689
6690 /// \brief Helper function to classify a mask as a single-input mask.
6691 ///
6692 /// This isn't a generic single-input test because in the vector shuffle
6693 /// lowering we canonicalize single inputs to be the first input operand. This
6694 /// means we can more quickly test for a single input by only checking whether
6695 /// an input from the second operand exists. We also assume that the size of
6696 /// mask corresponds to the size of the input vectors which isn't true in the
6697 /// fully general case.
6698 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6699   for (int M : Mask)
6700     if (M >= (int)Mask.size())
6701       return false;
6702   return true;
6703 }
6704
6705 /// \brief Test whether there are elements crossing 128-bit lanes in this
6706 /// shuffle mask.
6707 ///
6708 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6709 /// and we routinely test for these.
6710 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6711   int LaneSize = 128 / VT.getScalarSizeInBits();
6712   int Size = Mask.size();
6713   for (int i = 0; i < Size; ++i)
6714     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6715       return true;
6716   return false;
6717 }
6718
6719 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6720 ///
6721 /// This checks a shuffle mask to see if it is performing the same
6722 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6723 /// that it is also not lane-crossing. It may however involve a blend from the
6724 /// same lane of a second vector.
6725 ///
6726 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6727 /// non-trivial to compute in the face of undef lanes. The representation is
6728 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6729 /// entries from both V1 and V2 inputs to the wider mask.
6730 static bool
6731 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6732                                 SmallVectorImpl<int> &RepeatedMask) {
6733   int LaneSize = 128 / VT.getScalarSizeInBits();
6734   RepeatedMask.resize(LaneSize, -1);
6735   int Size = Mask.size();
6736   for (int i = 0; i < Size; ++i) {
6737     if (Mask[i] < 0)
6738       continue;
6739     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6740       // This entry crosses lanes, so there is no way to model this shuffle.
6741       return false;
6742
6743     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6744     if (RepeatedMask[i % LaneSize] == -1)
6745       // This is the first non-undef entry in this slot of a 128-bit lane.
6746       RepeatedMask[i % LaneSize] =
6747           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6748     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6749       // Found a mismatch with the repeated mask.
6750       return false;
6751   }
6752   return true;
6753 }
6754
6755 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6756 /// arguments.
6757 ///
6758 /// This is a fast way to test a shuffle mask against a fixed pattern:
6759 ///
6760 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6761 ///
6762 /// It returns true if the mask is exactly as wide as the argument list, and
6763 /// each element of the mask is either -1 (signifying undef) or the value given
6764 /// in the argument.
6765 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6766                                 ArrayRef<int> ExpectedMask) {
6767   if (Mask.size() != ExpectedMask.size())
6768     return false;
6769
6770   int Size = Mask.size();
6771
6772   // If the values are build vectors, we can look through them to find
6773   // equivalent inputs that make the shuffles equivalent.
6774   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6775   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6776
6777   for (int i = 0; i < Size; ++i)
6778     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6779       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6780       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6781       if (!MaskBV || !ExpectedBV ||
6782           MaskBV->getOperand(Mask[i] % Size) !=
6783               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6784         return false;
6785     }
6786
6787   return true;
6788 }
6789
6790 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6791 ///
6792 /// This helper function produces an 8-bit shuffle immediate corresponding to
6793 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6794 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6795 /// example.
6796 ///
6797 /// NB: We rely heavily on "undef" masks preserving the input lane.
6798 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6799                                           SelectionDAG &DAG) {
6800   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6801   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6802   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6803   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6804   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6805
6806   unsigned Imm = 0;
6807   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6808   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6809   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6810   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6811   return DAG.getConstant(Imm, DL, MVT::i8);
6812 }
6813
6814 /// \brief Compute whether each element of a shuffle is zeroable.
6815 ///
6816 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6817 /// Either it is an undef element in the shuffle mask, the element of the input
6818 /// referenced is undef, or the element of the input referenced is known to be
6819 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6820 /// as many lanes with this technique as possible to simplify the remaining
6821 /// shuffle.
6822 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6823                                                      SDValue V1, SDValue V2) {
6824   SmallBitVector Zeroable(Mask.size(), false);
6825
6826   while (V1.getOpcode() == ISD::BITCAST)
6827     V1 = V1->getOperand(0);
6828   while (V2.getOpcode() == ISD::BITCAST)
6829     V2 = V2->getOperand(0);
6830
6831   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6832   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6833
6834   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6835     int M = Mask[i];
6836     // Handle the easy cases.
6837     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6838       Zeroable[i] = true;
6839       continue;
6840     }
6841
6842     // If this is an index into a build_vector node (which has the same number
6843     // of elements), dig out the input value and use it.
6844     SDValue V = M < Size ? V1 : V2;
6845     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6846       continue;
6847
6848     SDValue Input = V.getOperand(M % Size);
6849     // The UNDEF opcode check really should be dead code here, but not quite
6850     // worth asserting on (it isn't invalid, just unexpected).
6851     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6852       Zeroable[i] = true;
6853   }
6854
6855   return Zeroable;
6856 }
6857
6858 // X86 has dedicated unpack instructions that can handle specific blend
6859 // operations: UNPCKH and UNPCKL.
6860 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6861                                            SDValue V1, SDValue V2,
6862                                            SelectionDAG &DAG) {
6863   int NumElts = VT.getVectorNumElements();
6864   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6865   SmallVector<int, 8> Unpckl;
6866   SmallVector<int, 8> Unpckh;
6867
6868   for (int i = 0; i < NumElts; ++i) {
6869     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6870     int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6871     int HiPos = LoPos + NumEltsInLane / 2;
6872     Unpckl.push_back(LoPos);
6873     Unpckh.push_back(HiPos);
6874   }
6875
6876   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6877     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6878   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6879     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6880
6881   // Commute and try again.
6882   ShuffleVectorSDNode::commuteMask(Unpckl);
6883   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6884     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6885
6886   ShuffleVectorSDNode::commuteMask(Unpckh);
6887   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6888     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6889
6890   return SDValue();
6891 }
6892
6893 /// \brief Try to emit a bitmask instruction for a shuffle.
6894 ///
6895 /// This handles cases where we can model a blend exactly as a bitmask due to
6896 /// one of the inputs being zeroable.
6897 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6898                                            SDValue V2, ArrayRef<int> Mask,
6899                                            SelectionDAG &DAG) {
6900   MVT EltVT = VT.getVectorElementType();
6901   int NumEltBits = EltVT.getSizeInBits();
6902   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6903   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6904   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6905                                     IntEltVT);
6906   if (EltVT.isFloatingPoint()) {
6907     Zero = DAG.getBitcast(EltVT, Zero);
6908     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6909   }
6910   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6911   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6912   SDValue V;
6913   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6914     if (Zeroable[i])
6915       continue;
6916     if (Mask[i] % Size != i)
6917       return SDValue(); // Not a blend.
6918     if (!V)
6919       V = Mask[i] < Size ? V1 : V2;
6920     else if (V != (Mask[i] < Size ? V1 : V2))
6921       return SDValue(); // Can only let one input through the mask.
6922
6923     VMaskOps[i] = AllOnes;
6924   }
6925   if (!V)
6926     return SDValue(); // No non-zeroable elements!
6927
6928   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6929   V = DAG.getNode(VT.isFloatingPoint()
6930                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6931                   DL, VT, V, VMask);
6932   return V;
6933 }
6934
6935 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6936 ///
6937 /// This is used as a fallback approach when first class blend instructions are
6938 /// unavailable. Currently it is only suitable for integer vectors, but could
6939 /// be generalized for floating point vectors if desirable.
6940 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6941                                             SDValue V2, ArrayRef<int> Mask,
6942                                             SelectionDAG &DAG) {
6943   assert(VT.isInteger() && "Only supports integer vector types!");
6944   MVT EltVT = VT.getVectorElementType();
6945   int NumEltBits = EltVT.getSizeInBits();
6946   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6947   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6948                                     EltVT);
6949   SmallVector<SDValue, 16> MaskOps;
6950   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6951     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6952       return SDValue(); // Shuffled input!
6953     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6954   }
6955
6956   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6957   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6958   // We have to cast V2 around.
6959   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6960   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6961                                       DAG.getBitcast(MaskVT, V1Mask),
6962                                       DAG.getBitcast(MaskVT, V2)));
6963   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6964 }
6965
6966 /// \brief Try to emit a blend instruction for a shuffle.
6967 ///
6968 /// This doesn't do any checks for the availability of instructions for blending
6969 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6970 /// be matched in the backend with the type given. What it does check for is
6971 /// that the shuffle mask is a blend, or convertible into a blend with zero.
6972 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6973                                          SDValue V2, ArrayRef<int> Original,
6974                                          const X86Subtarget *Subtarget,
6975                                          SelectionDAG &DAG) {
6976   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6977   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6978   SmallVector<int, 8> Mask(Original.begin(), Original.end());
6979   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6980   bool ForceV1Zero = false, ForceV2Zero = false;
6981
6982   // Attempt to generate the binary blend mask. If an input is zero then
6983   // we can use any lane.
6984   // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
6985   unsigned BlendMask = 0;
6986   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6987     int M = Mask[i];
6988     if (M < 0)
6989       continue;
6990     if (M == i)
6991       continue;
6992     if (M == i + Size) {
6993       BlendMask |= 1u << i;
6994       continue;
6995     }
6996     if (Zeroable[i]) {
6997       if (V1IsZero) {
6998         ForceV1Zero = true;
6999         Mask[i] = i;
7000         continue;
7001       }
7002       if (V2IsZero) {
7003         ForceV2Zero = true;
7004         BlendMask |= 1u << i;
7005         Mask[i] = i + Size;
7006         continue;
7007       }
7008     }
7009     return SDValue(); // Shuffled input!
7010   }
7011
7012   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7013   if (ForceV1Zero)
7014     V1 = getZeroVector(VT, Subtarget, DAG, DL);
7015   if (ForceV2Zero)
7016     V2 = getZeroVector(VT, Subtarget, DAG, DL);
7017
7018   auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7019     unsigned ScaledMask = 0;
7020     for (int i = 0; i != Size; ++i)
7021       if (BlendMask & (1u << i))
7022         for (int j = 0; j != Scale; ++j)
7023           ScaledMask |= 1u << (i * Scale + j);
7024     return ScaledMask;
7025   };
7026
7027   switch (VT.SimpleTy) {
7028   case MVT::v2f64:
7029   case MVT::v4f32:
7030   case MVT::v4f64:
7031   case MVT::v8f32:
7032     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7033                        DAG.getConstant(BlendMask, DL, MVT::i8));
7034
7035   case MVT::v4i64:
7036   case MVT::v8i32:
7037     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7038     // FALLTHROUGH
7039   case MVT::v2i64:
7040   case MVT::v4i32:
7041     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7042     // that instruction.
7043     if (Subtarget->hasAVX2()) {
7044       // Scale the blend by the number of 32-bit dwords per element.
7045       int Scale =  VT.getScalarSizeInBits() / 32;
7046       BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7047       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7048       V1 = DAG.getBitcast(BlendVT, V1);
7049       V2 = DAG.getBitcast(BlendVT, V2);
7050       return DAG.getBitcast(
7051           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7052                           DAG.getConstant(BlendMask, DL, MVT::i8)));
7053     }
7054     // FALLTHROUGH
7055   case MVT::v8i16: {
7056     // For integer shuffles we need to expand the mask and cast the inputs to
7057     // v8i16s prior to blending.
7058     int Scale = 8 / VT.getVectorNumElements();
7059     BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7060     V1 = DAG.getBitcast(MVT::v8i16, V1);
7061     V2 = DAG.getBitcast(MVT::v8i16, V2);
7062     return DAG.getBitcast(VT,
7063                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7064                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
7065   }
7066
7067   case MVT::v16i16: {
7068     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7069     SmallVector<int, 8> RepeatedMask;
7070     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7071       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7072       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7073       BlendMask = 0;
7074       for (int i = 0; i < 8; ++i)
7075         if (RepeatedMask[i] >= 16)
7076           BlendMask |= 1u << i;
7077       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7078                          DAG.getConstant(BlendMask, DL, MVT::i8));
7079     }
7080   }
7081     // FALLTHROUGH
7082   case MVT::v16i8:
7083   case MVT::v32i8: {
7084     assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7085            "256-bit byte-blends require AVX2 support!");
7086
7087     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7088     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7089       return Masked;
7090
7091     // Scale the blend by the number of bytes per element.
7092     int Scale = VT.getScalarSizeInBits() / 8;
7093
7094     // This form of blend is always done on bytes. Compute the byte vector
7095     // type.
7096     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7097
7098     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7099     // mix of LLVM's code generator and the x86 backend. We tell the code
7100     // generator that boolean values in the elements of an x86 vector register
7101     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7102     // mapping a select to operand #1, and 'false' mapping to operand #2. The
7103     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7104     // of the element (the remaining are ignored) and 0 in that high bit would
7105     // mean operand #1 while 1 in the high bit would mean operand #2. So while
7106     // the LLVM model for boolean values in vector elements gets the relevant
7107     // bit set, it is set backwards and over constrained relative to x86's
7108     // actual model.
7109     SmallVector<SDValue, 32> VSELECTMask;
7110     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7111       for (int j = 0; j < Scale; ++j)
7112         VSELECTMask.push_back(
7113             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7114                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7115                                           MVT::i8));
7116
7117     V1 = DAG.getBitcast(BlendVT, V1);
7118     V2 = DAG.getBitcast(BlendVT, V2);
7119     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7120                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
7121                                                       BlendVT, VSELECTMask),
7122                                           V1, V2));
7123   }
7124
7125   default:
7126     llvm_unreachable("Not a supported integer vector type!");
7127   }
7128 }
7129
7130 /// \brief Try to lower as a blend of elements from two inputs followed by
7131 /// a single-input permutation.
7132 ///
7133 /// This matches the pattern where we can blend elements from two inputs and
7134 /// then reduce the shuffle to a single-input permutation.
7135 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7136                                                    SDValue V2,
7137                                                    ArrayRef<int> Mask,
7138                                                    SelectionDAG &DAG) {
7139   // We build up the blend mask while checking whether a blend is a viable way
7140   // to reduce the shuffle.
7141   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7142   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7143
7144   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7145     if (Mask[i] < 0)
7146       continue;
7147
7148     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7149
7150     if (BlendMask[Mask[i] % Size] == -1)
7151       BlendMask[Mask[i] % Size] = Mask[i];
7152     else if (BlendMask[Mask[i] % Size] != Mask[i])
7153       return SDValue(); // Can't blend in the needed input!
7154
7155     PermuteMask[i] = Mask[i] % Size;
7156   }
7157
7158   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7159   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7160 }
7161
7162 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7163 /// blends and permutes.
7164 ///
7165 /// This matches the extremely common pattern for handling combined
7166 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7167 /// operations. It will try to pick the best arrangement of shuffles and
7168 /// blends.
7169 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7170                                                           SDValue V1,
7171                                                           SDValue V2,
7172                                                           ArrayRef<int> Mask,
7173                                                           SelectionDAG &DAG) {
7174   // Shuffle the input elements into the desired positions in V1 and V2 and
7175   // blend them together.
7176   SmallVector<int, 32> V1Mask(Mask.size(), -1);
7177   SmallVector<int, 32> V2Mask(Mask.size(), -1);
7178   SmallVector<int, 32> BlendMask(Mask.size(), -1);
7179   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7180     if (Mask[i] >= 0 && Mask[i] < Size) {
7181       V1Mask[i] = Mask[i];
7182       BlendMask[i] = i;
7183     } else if (Mask[i] >= Size) {
7184       V2Mask[i] = Mask[i] - Size;
7185       BlendMask[i] = i + Size;
7186     }
7187
7188   // Try to lower with the simpler initial blend strategy unless one of the
7189   // input shuffles would be a no-op. We prefer to shuffle inputs as the
7190   // shuffle may be able to fold with a load or other benefit. However, when
7191   // we'll have to do 2x as many shuffles in order to achieve this, blending
7192   // first is a better strategy.
7193   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7194     if (SDValue BlendPerm =
7195             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7196       return BlendPerm;
7197
7198   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7199   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7200   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7201 }
7202
7203 /// \brief Try to lower a vector shuffle as a byte rotation.
7204 ///
7205 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7206 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7207 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7208 /// try to generically lower a vector shuffle through such an pattern. It
7209 /// does not check for the profitability of lowering either as PALIGNR or
7210 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7211 /// This matches shuffle vectors that look like:
7212 ///
7213 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7214 ///
7215 /// Essentially it concatenates V1 and V2, shifts right by some number of
7216 /// elements, and takes the low elements as the result. Note that while this is
7217 /// specified as a *right shift* because x86 is little-endian, it is a *left
7218 /// rotate* of the vector lanes.
7219 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7220                                               SDValue V2,
7221                                               ArrayRef<int> Mask,
7222                                               const X86Subtarget *Subtarget,
7223                                               SelectionDAG &DAG) {
7224   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7225
7226   int NumElts = Mask.size();
7227   int NumLanes = VT.getSizeInBits() / 128;
7228   int NumLaneElts = NumElts / NumLanes;
7229
7230   // We need to detect various ways of spelling a rotation:
7231   //   [11, 12, 13, 14, 15,  0,  1,  2]
7232   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7233   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7234   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7235   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7236   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7237   int Rotation = 0;
7238   SDValue Lo, Hi;
7239   for (int l = 0; l < NumElts; l += NumLaneElts) {
7240     for (int i = 0; i < NumLaneElts; ++i) {
7241       if (Mask[l + i] == -1)
7242         continue;
7243       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7244
7245       // Get the mod-Size index and lane correct it.
7246       int LaneIdx = (Mask[l + i] % NumElts) - l;
7247       // Make sure it was in this lane.
7248       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7249         return SDValue();
7250
7251       // Determine where a rotated vector would have started.
7252       int StartIdx = i - LaneIdx;
7253       if (StartIdx == 0)
7254         // The identity rotation isn't interesting, stop.
7255         return SDValue();
7256
7257       // If we found the tail of a vector the rotation must be the missing
7258       // front. If we found the head of a vector, it must be how much of the
7259       // head.
7260       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7261
7262       if (Rotation == 0)
7263         Rotation = CandidateRotation;
7264       else if (Rotation != CandidateRotation)
7265         // The rotations don't match, so we can't match this mask.
7266         return SDValue();
7267
7268       // Compute which value this mask is pointing at.
7269       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7270
7271       // Compute which of the two target values this index should be assigned
7272       // to. This reflects whether the high elements are remaining or the low
7273       // elements are remaining.
7274       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7275
7276       // Either set up this value if we've not encountered it before, or check
7277       // that it remains consistent.
7278       if (!TargetV)
7279         TargetV = MaskV;
7280       else if (TargetV != MaskV)
7281         // This may be a rotation, but it pulls from the inputs in some
7282         // unsupported interleaving.
7283         return SDValue();
7284     }
7285   }
7286
7287   // Check that we successfully analyzed the mask, and normalize the results.
7288   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7289   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7290   if (!Lo)
7291     Lo = Hi;
7292   else if (!Hi)
7293     Hi = Lo;
7294
7295   // The actual rotate instruction rotates bytes, so we need to scale the
7296   // rotation based on how many bytes are in the vector lane.
7297   int Scale = 16 / NumLaneElts;
7298
7299   // SSSE3 targets can use the palignr instruction.
7300   if (Subtarget->hasSSSE3()) {
7301     // Cast the inputs to i8 vector of correct length to match PALIGNR.
7302     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7303     Lo = DAG.getBitcast(AlignVT, Lo);
7304     Hi = DAG.getBitcast(AlignVT, Hi);
7305
7306     return DAG.getBitcast(
7307         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7308                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7309   }
7310
7311   assert(VT.is128BitVector() &&
7312          "Rotate-based lowering only supports 128-bit lowering!");
7313   assert(Mask.size() <= 16 &&
7314          "Can shuffle at most 16 bytes in a 128-bit vector!");
7315
7316   // Default SSE2 implementation
7317   int LoByteShift = 16 - Rotation * Scale;
7318   int HiByteShift = Rotation * Scale;
7319
7320   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7321   Lo = DAG.getBitcast(MVT::v2i64, Lo);
7322   Hi = DAG.getBitcast(MVT::v2i64, Hi);
7323
7324   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7325                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
7326   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7327                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
7328   return DAG.getBitcast(VT,
7329                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7330 }
7331
7332 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7333 ///
7334 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7335 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7336 /// matches elements from one of the input vectors shuffled to the left or
7337 /// right with zeroable elements 'shifted in'. It handles both the strictly
7338 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7339 /// quad word lane.
7340 ///
7341 /// PSHL : (little-endian) left bit shift.
7342 /// [ zz, 0, zz,  2 ]
7343 /// [ -1, 4, zz, -1 ]
7344 /// PSRL : (little-endian) right bit shift.
7345 /// [  1, zz,  3, zz]
7346 /// [ -1, -1,  7, zz]
7347 /// PSLLDQ : (little-endian) left byte shift
7348 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
7349 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
7350 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
7351 /// PSRLDQ : (little-endian) right byte shift
7352 /// [  5, 6,  7, zz, zz, zz, zz, zz]
7353 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
7354 /// [  1, 2, -1, -1, -1, -1, zz, zz]
7355 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7356                                          SDValue V2, ArrayRef<int> Mask,
7357                                          SelectionDAG &DAG) {
7358   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7359
7360   int Size = Mask.size();
7361   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7362
7363   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7364     for (int i = 0; i < Size; i += Scale)
7365       for (int j = 0; j < Shift; ++j)
7366         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7367           return false;
7368
7369     return true;
7370   };
7371
7372   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7373     for (int i = 0; i != Size; i += Scale) {
7374       unsigned Pos = Left ? i + Shift : i;
7375       unsigned Low = Left ? i : i + Shift;
7376       unsigned Len = Scale - Shift;
7377       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7378                                       Low + (V == V1 ? 0 : Size)))
7379         return SDValue();
7380     }
7381
7382     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7383     bool ByteShift = ShiftEltBits > 64;
7384     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7385                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7386     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7387
7388     // Normalize the scale for byte shifts to still produce an i64 element
7389     // type.
7390     Scale = ByteShift ? Scale / 2 : Scale;
7391
7392     // We need to round trip through the appropriate type for the shift.
7393     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7394     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7395     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7396            "Illegal integer vector type");
7397     V = DAG.getBitcast(ShiftVT, V);
7398
7399     V = DAG.getNode(OpCode, DL, ShiftVT, V,
7400                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
7401     return DAG.getBitcast(VT, V);
7402   };
7403
7404   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7405   // keep doubling the size of the integer elements up to that. We can
7406   // then shift the elements of the integer vector by whole multiples of
7407   // their width within the elements of the larger integer vector. Test each
7408   // multiple to see if we can find a match with the moved element indices
7409   // and that the shifted in elements are all zeroable.
7410   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7411     for (int Shift = 1; Shift != Scale; ++Shift)
7412       for (bool Left : {true, false})
7413         if (CheckZeros(Shift, Scale, Left))
7414           for (SDValue V : {V1, V2})
7415             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7416               return Match;
7417
7418   // no match
7419   return SDValue();
7420 }
7421
7422 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7423 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7424                                            SDValue V2, ArrayRef<int> Mask,
7425                                            SelectionDAG &DAG) {
7426   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7427   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7428
7429   int Size = Mask.size();
7430   int HalfSize = Size / 2;
7431   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7432
7433   // Upper half must be undefined.
7434   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7435     return SDValue();
7436
7437   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7438   // Remainder of lower half result is zero and upper half is all undef.
7439   auto LowerAsEXTRQ = [&]() {
7440     // Determine the extraction length from the part of the
7441     // lower half that isn't zeroable.
7442     int Len = HalfSize;
7443     for (; Len > 0; --Len)
7444       if (!Zeroable[Len - 1])
7445         break;
7446     assert(Len > 0 && "Zeroable shuffle mask");
7447
7448     // Attempt to match first Len sequential elements from the lower half.
7449     SDValue Src;
7450     int Idx = -1;
7451     for (int i = 0; i != Len; ++i) {
7452       int M = Mask[i];
7453       if (M < 0)
7454         continue;
7455       SDValue &V = (M < Size ? V1 : V2);
7456       M = M % Size;
7457
7458       // The extracted elements must start at a valid index and all mask
7459       // elements must be in the lower half.
7460       if (i > M || M >= HalfSize)
7461         return SDValue();
7462
7463       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7464         Src = V;
7465         Idx = M - i;
7466         continue;
7467       }
7468       return SDValue();
7469     }
7470
7471     if (Idx < 0)
7472       return SDValue();
7473
7474     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7475     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7476     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7477     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7478                        DAG.getConstant(BitLen, DL, MVT::i8),
7479                        DAG.getConstant(BitIdx, DL, MVT::i8));
7480   };
7481
7482   if (SDValue ExtrQ = LowerAsEXTRQ())
7483     return ExtrQ;
7484
7485   // INSERTQ: Extract lowest Len elements from lower half of second source and
7486   // insert over first source, starting at Idx.
7487   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7488   auto LowerAsInsertQ = [&]() {
7489     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7490       SDValue Base;
7491
7492       // Attempt to match first source from mask before insertion point.
7493       if (isUndefInRange(Mask, 0, Idx)) {
7494         /* EMPTY */
7495       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7496         Base = V1;
7497       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7498         Base = V2;
7499       } else {
7500         continue;
7501       }
7502
7503       // Extend the extraction length looking to match both the insertion of
7504       // the second source and the remaining elements of the first.
7505       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7506         SDValue Insert;
7507         int Len = Hi - Idx;
7508
7509         // Match insertion.
7510         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7511           Insert = V1;
7512         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7513           Insert = V2;
7514         } else {
7515           continue;
7516         }
7517
7518         // Match the remaining elements of the lower half.
7519         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7520           /* EMPTY */
7521         } else if ((!Base || (Base == V1)) &&
7522                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7523           Base = V1;
7524         } else if ((!Base || (Base == V2)) &&
7525                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7526                                               Size + Hi)) {
7527           Base = V2;
7528         } else {
7529           continue;
7530         }
7531
7532         // We may not have a base (first source) - this can safely be undefined.
7533         if (!Base)
7534           Base = DAG.getUNDEF(VT);
7535
7536         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7537         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7538         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7539                            DAG.getConstant(BitLen, DL, MVT::i8),
7540                            DAG.getConstant(BitIdx, DL, MVT::i8));
7541       }
7542     }
7543
7544     return SDValue();
7545   };
7546
7547   if (SDValue InsertQ = LowerAsInsertQ())
7548     return InsertQ;
7549
7550   return SDValue();
7551 }
7552
7553 /// \brief Lower a vector shuffle as a zero or any extension.
7554 ///
7555 /// Given a specific number of elements, element bit width, and extension
7556 /// stride, produce either a zero or any extension based on the available
7557 /// features of the subtarget. The extended elements are consecutive and
7558 /// begin and can start from an offseted element index in the input; to
7559 /// avoid excess shuffling the offset must either being in the bottom lane
7560 /// or at the start of a higher lane. All extended elements must be from
7561 /// the same lane.
7562 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7563     SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7564     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7565   assert(Scale > 1 && "Need a scale to extend.");
7566   int EltBits = VT.getScalarSizeInBits();
7567   int NumElements = VT.getVectorNumElements();
7568   int NumEltsPerLane = 128 / EltBits;
7569   int OffsetLane = Offset / NumEltsPerLane;
7570   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7571          "Only 8, 16, and 32 bit elements can be extended.");
7572   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7573   assert(0 <= Offset && "Extension offset must be positive.");
7574   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7575          "Extension offset must be in the first lane or start an upper lane.");
7576
7577   // Check that an index is in same lane as the base offset.
7578   auto SafeOffset = [&](int Idx) {
7579     return OffsetLane == (Idx / NumEltsPerLane);
7580   };
7581
7582   // Shift along an input so that the offset base moves to the first element.
7583   auto ShuffleOffset = [&](SDValue V) {
7584     if (!Offset)
7585       return V;
7586
7587     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7588     for (int i = 0; i * Scale < NumElements; ++i) {
7589       int SrcIdx = i + Offset;
7590       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7591     }
7592     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7593   };
7594
7595   // Found a valid zext mask! Try various lowering strategies based on the
7596   // input type and available ISA extensions.
7597   if (Subtarget->hasSSE41()) {
7598     // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7599     // PUNPCK will catch this in a later shuffle match.
7600     if (Offset && Scale == 2 && VT.is128BitVector())
7601       return SDValue();
7602     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7603                                  NumElements / Scale);
7604     InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7605     return DAG.getBitcast(VT, InputV);
7606   }
7607
7608   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7609
7610   // For any extends we can cheat for larger element sizes and use shuffle
7611   // instructions that can fold with a load and/or copy.
7612   if (AnyExt && EltBits == 32) {
7613     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7614                          -1};
7615     return DAG.getBitcast(
7616         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7617                         DAG.getBitcast(MVT::v4i32, InputV),
7618                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7619   }
7620   if (AnyExt && EltBits == 16 && Scale > 2) {
7621     int PSHUFDMask[4] = {Offset / 2, -1,
7622                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7623     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7624                          DAG.getBitcast(MVT::v4i32, InputV),
7625                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7626     int PSHUFWMask[4] = {1, -1, -1, -1};
7627     unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7628     return DAG.getBitcast(
7629         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7630                         DAG.getBitcast(MVT::v8i16, InputV),
7631                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7632   }
7633
7634   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7635   // to 64-bits.
7636   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7637     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7638     assert(VT.is128BitVector() && "Unexpected vector width!");
7639
7640     int LoIdx = Offset * EltBits;
7641     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7642                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7643                                          DAG.getConstant(EltBits, DL, MVT::i8),
7644                                          DAG.getConstant(LoIdx, DL, MVT::i8)));
7645
7646     if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7647         !SafeOffset(Offset + 1))
7648       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7649
7650     int HiIdx = (Offset + 1) * EltBits;
7651     SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7652                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7653                                          DAG.getConstant(EltBits, DL, MVT::i8),
7654                                          DAG.getConstant(HiIdx, DL, MVT::i8)));
7655     return DAG.getNode(ISD::BITCAST, DL, VT,
7656                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7657   }
7658
7659   // If this would require more than 2 unpack instructions to expand, use
7660   // pshufb when available. We can only use more than 2 unpack instructions
7661   // when zero extending i8 elements which also makes it easier to use pshufb.
7662   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7663     assert(NumElements == 16 && "Unexpected byte vector width!");
7664     SDValue PSHUFBMask[16];
7665     for (int i = 0; i < 16; ++i) {
7666       int Idx = Offset + (i / Scale);
7667       PSHUFBMask[i] = DAG.getConstant(
7668           (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7669     }
7670     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7671     return DAG.getBitcast(VT,
7672                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7673                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7674                                                   MVT::v16i8, PSHUFBMask)));
7675   }
7676
7677   // If we are extending from an offset, ensure we start on a boundary that
7678   // we can unpack from.
7679   int AlignToUnpack = Offset % (NumElements / Scale);
7680   if (AlignToUnpack) {
7681     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7682     for (int i = AlignToUnpack; i < NumElements; ++i)
7683       ShMask[i - AlignToUnpack] = i;
7684     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7685     Offset -= AlignToUnpack;
7686   }
7687
7688   // Otherwise emit a sequence of unpacks.
7689   do {
7690     unsigned UnpackLoHi = X86ISD::UNPCKL;
7691     if (Offset >= (NumElements / 2)) {
7692       UnpackLoHi = X86ISD::UNPCKH;
7693       Offset -= (NumElements / 2);
7694     }
7695
7696     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7697     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7698                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7699     InputV = DAG.getBitcast(InputVT, InputV);
7700     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7701     Scale /= 2;
7702     EltBits *= 2;
7703     NumElements /= 2;
7704   } while (Scale > 1);
7705   return DAG.getBitcast(VT, InputV);
7706 }
7707
7708 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7709 ///
7710 /// This routine will try to do everything in its power to cleverly lower
7711 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7712 /// check for the profitability of this lowering,  it tries to aggressively
7713 /// match this pattern. It will use all of the micro-architectural details it
7714 /// can to emit an efficient lowering. It handles both blends with all-zero
7715 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7716 /// masking out later).
7717 ///
7718 /// The reason we have dedicated lowering for zext-style shuffles is that they
7719 /// are both incredibly common and often quite performance sensitive.
7720 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7721     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7722     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7723   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7724
7725   int Bits = VT.getSizeInBits();
7726   int NumLanes = Bits / 128;
7727   int NumElements = VT.getVectorNumElements();
7728   int NumEltsPerLane = NumElements / NumLanes;
7729   assert(VT.getScalarSizeInBits() <= 32 &&
7730          "Exceeds 32-bit integer zero extension limit");
7731   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7732
7733   // Define a helper function to check a particular ext-scale and lower to it if
7734   // valid.
7735   auto Lower = [&](int Scale) -> SDValue {
7736     SDValue InputV;
7737     bool AnyExt = true;
7738     int Offset = 0;
7739     int Matches = 0;
7740     for (int i = 0; i < NumElements; ++i) {
7741       int M = Mask[i];
7742       if (M == -1)
7743         continue; // Valid anywhere but doesn't tell us anything.
7744       if (i % Scale != 0) {
7745         // Each of the extended elements need to be zeroable.
7746         if (!Zeroable[i])
7747           return SDValue();
7748
7749         // We no longer are in the anyext case.
7750         AnyExt = false;
7751         continue;
7752       }
7753
7754       // Each of the base elements needs to be consecutive indices into the
7755       // same input vector.
7756       SDValue V = M < NumElements ? V1 : V2;
7757       M = M % NumElements;
7758       if (!InputV) {
7759         InputV = V;
7760         Offset = M - (i / Scale);
7761       } else if (InputV != V)
7762         return SDValue(); // Flip-flopping inputs.
7763
7764       // Offset must start in the lowest 128-bit lane or at the start of an
7765       // upper lane.
7766       // FIXME: Is it ever worth allowing a negative base offset?
7767       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7768             (Offset % NumEltsPerLane) == 0))
7769         return SDValue();
7770
7771       // If we are offsetting, all referenced entries must come from the same
7772       // lane.
7773       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7774         return SDValue();
7775
7776       if ((M % NumElements) != (Offset + (i / Scale)))
7777         return SDValue(); // Non-consecutive strided elements.
7778       Matches++;
7779     }
7780
7781     // If we fail to find an input, we have a zero-shuffle which should always
7782     // have already been handled.
7783     // FIXME: Maybe handle this here in case during blending we end up with one?
7784     if (!InputV)
7785       return SDValue();
7786
7787     // If we are offsetting, don't extend if we only match a single input, we
7788     // can always do better by using a basic PSHUF or PUNPCK.
7789     if (Offset != 0 && Matches < 2)
7790       return SDValue();
7791
7792     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7793         DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7794   };
7795
7796   // The widest scale possible for extending is to a 64-bit integer.
7797   assert(Bits % 64 == 0 &&
7798          "The number of bits in a vector must be divisible by 64 on x86!");
7799   int NumExtElements = Bits / 64;
7800
7801   // Each iteration, try extending the elements half as much, but into twice as
7802   // many elements.
7803   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7804     assert(NumElements % NumExtElements == 0 &&
7805            "The input vector size must be divisible by the extended size.");
7806     if (SDValue V = Lower(NumElements / NumExtElements))
7807       return V;
7808   }
7809
7810   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7811   if (Bits != 128)
7812     return SDValue();
7813
7814   // Returns one of the source operands if the shuffle can be reduced to a
7815   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7816   auto CanZExtLowHalf = [&]() {
7817     for (int i = NumElements / 2; i != NumElements; ++i)
7818       if (!Zeroable[i])
7819         return SDValue();
7820     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7821       return V1;
7822     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7823       return V2;
7824     return SDValue();
7825   };
7826
7827   if (SDValue V = CanZExtLowHalf()) {
7828     V = DAG.getBitcast(MVT::v2i64, V);
7829     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7830     return DAG.getBitcast(VT, V);
7831   }
7832
7833   // No viable ext lowering found.
7834   return SDValue();
7835 }
7836
7837 /// \brief Try to get a scalar value for a specific element of a vector.
7838 ///
7839 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7840 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7841                                               SelectionDAG &DAG) {
7842   MVT VT = V.getSimpleValueType();
7843   MVT EltVT = VT.getVectorElementType();
7844   while (V.getOpcode() == ISD::BITCAST)
7845     V = V.getOperand(0);
7846   // If the bitcasts shift the element size, we can't extract an equivalent
7847   // element from it.
7848   MVT NewVT = V.getSimpleValueType();
7849   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7850     return SDValue();
7851
7852   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7853       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7854     // Ensure the scalar operand is the same size as the destination.
7855     // FIXME: Add support for scalar truncation where possible.
7856     SDValue S = V.getOperand(Idx);
7857     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7858       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7859   }
7860
7861   return SDValue();
7862 }
7863
7864 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7865 ///
7866 /// This is particularly important because the set of instructions varies
7867 /// significantly based on whether the operand is a load or not.
7868 static bool isShuffleFoldableLoad(SDValue V) {
7869   while (V.getOpcode() == ISD::BITCAST)
7870     V = V.getOperand(0);
7871
7872   return ISD::isNON_EXTLoad(V.getNode());
7873 }
7874
7875 /// \brief Try to lower insertion of a single element into a zero vector.
7876 ///
7877 /// This is a common pattern that we have especially efficient patterns to lower
7878 /// across all subtarget feature sets.
7879 static SDValue lowerVectorShuffleAsElementInsertion(
7880     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7881     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7882   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7883   MVT ExtVT = VT;
7884   MVT EltVT = VT.getVectorElementType();
7885
7886   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7887                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7888                 Mask.begin();
7889   bool IsV1Zeroable = true;
7890   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7891     if (i != V2Index && !Zeroable[i]) {
7892       IsV1Zeroable = false;
7893       break;
7894     }
7895
7896   // Check for a single input from a SCALAR_TO_VECTOR node.
7897   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7898   // all the smarts here sunk into that routine. However, the current
7899   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7900   // vector shuffle lowering is dead.
7901   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7902                                                DAG);
7903   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7904     // We need to zext the scalar if it is smaller than an i32.
7905     V2S = DAG.getBitcast(EltVT, V2S);
7906     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7907       // Using zext to expand a narrow element won't work for non-zero
7908       // insertions.
7909       if (!IsV1Zeroable)
7910         return SDValue();
7911
7912       // Zero-extend directly to i32.
7913       ExtVT = MVT::v4i32;
7914       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7915     }
7916     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7917   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7918              EltVT == MVT::i16) {
7919     // Either not inserting from the low element of the input or the input
7920     // element size is too small to use VZEXT_MOVL to clear the high bits.
7921     return SDValue();
7922   }
7923
7924   if (!IsV1Zeroable) {
7925     // If V1 can't be treated as a zero vector we have fewer options to lower
7926     // this. We can't support integer vectors or non-zero targets cheaply, and
7927     // the V1 elements can't be permuted in any way.
7928     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7929     if (!VT.isFloatingPoint() || V2Index != 0)
7930       return SDValue();
7931     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7932     V1Mask[V2Index] = -1;
7933     if (!isNoopShuffleMask(V1Mask))
7934       return SDValue();
7935     // This is essentially a special case blend operation, but if we have
7936     // general purpose blend operations, they are always faster. Bail and let
7937     // the rest of the lowering handle these as blends.
7938     if (Subtarget->hasSSE41())
7939       return SDValue();
7940
7941     // Otherwise, use MOVSD or MOVSS.
7942     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7943            "Only two types of floating point element types to handle!");
7944     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7945                        ExtVT, V1, V2);
7946   }
7947
7948   // This lowering only works for the low element with floating point vectors.
7949   if (VT.isFloatingPoint() && V2Index != 0)
7950     return SDValue();
7951
7952   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7953   if (ExtVT != VT)
7954     V2 = DAG.getBitcast(VT, V2);
7955
7956   if (V2Index != 0) {
7957     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7958     // the desired position. Otherwise it is more efficient to do a vector
7959     // shift left. We know that we can do a vector shift left because all
7960     // the inputs are zero.
7961     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7962       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7963       V2Shuffle[V2Index] = 0;
7964       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7965     } else {
7966       V2 = DAG.getBitcast(MVT::v2i64, V2);
7967       V2 = DAG.getNode(
7968           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7969           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7970                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7971                               DAG.getDataLayout(), VT)));
7972       V2 = DAG.getBitcast(VT, V2);
7973     }
7974   }
7975   return V2;
7976 }
7977
7978 /// \brief Try to lower broadcast of a single - truncated - integer element,
7979 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
7980 ///
7981 /// This assumes we have AVX2.
7982 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
7983                                                   int BroadcastIdx,
7984                                                   const X86Subtarget *Subtarget,
7985                                                   SelectionDAG &DAG) {
7986   assert(Subtarget->hasAVX2() &&
7987          "We can only lower integer broadcasts with AVX2!");
7988
7989   EVT EltVT = VT.getVectorElementType();
7990   EVT V0VT = V0.getValueType();
7991
7992   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
7993   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
7994
7995   EVT V0EltVT = V0VT.getVectorElementType();
7996   if (!V0EltVT.isInteger())
7997     return SDValue();
7998
7999   const unsigned EltSize = EltVT.getSizeInBits();
8000   const unsigned V0EltSize = V0EltVT.getSizeInBits();
8001
8002   // This is only a truncation if the original element type is larger.
8003   if (V0EltSize <= EltSize)
8004     return SDValue();
8005
8006   assert(((V0EltSize % EltSize) == 0) &&
8007          "Scalar type sizes must all be powers of 2 on x86!");
8008
8009   const unsigned V0Opc = V0.getOpcode();
8010   const unsigned Scale = V0EltSize / EltSize;
8011   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8012
8013   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8014       V0Opc != ISD::BUILD_VECTOR)
8015     return SDValue();
8016
8017   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8018
8019   // If we're extracting non-least-significant bits, shift so we can truncate.
8020   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8021   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8022   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8023   if (const int OffsetIdx = BroadcastIdx % Scale)
8024     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8025             DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8026
8027   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8028                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8029 }
8030
8031 /// \brief Try to lower broadcast of a single element.
8032 ///
8033 /// For convenience, this code also bundles all of the subtarget feature set
8034 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8035 /// a convenient way to factor it out.
8036 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8037                                              ArrayRef<int> Mask,
8038                                              const X86Subtarget *Subtarget,
8039                                              SelectionDAG &DAG) {
8040   if (!Subtarget->hasAVX())
8041     return SDValue();
8042   if (VT.isInteger() && !Subtarget->hasAVX2())
8043     return SDValue();
8044
8045   // Check that the mask is a broadcast.
8046   int BroadcastIdx = -1;
8047   for (int M : Mask)
8048     if (M >= 0 && BroadcastIdx == -1)
8049       BroadcastIdx = M;
8050     else if (M >= 0 && M != BroadcastIdx)
8051       return SDValue();
8052
8053   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8054                                             "a sorted mask where the broadcast "
8055                                             "comes from V1.");
8056
8057   // Go up the chain of (vector) values to find a scalar load that we can
8058   // combine with the broadcast.
8059   for (;;) {
8060     switch (V.getOpcode()) {
8061     case ISD::CONCAT_VECTORS: {
8062       int OperandSize = Mask.size() / V.getNumOperands();
8063       V = V.getOperand(BroadcastIdx / OperandSize);
8064       BroadcastIdx %= OperandSize;
8065       continue;
8066     }
8067
8068     case ISD::INSERT_SUBVECTOR: {
8069       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8070       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8071       if (!ConstantIdx)
8072         break;
8073
8074       int BeginIdx = (int)ConstantIdx->getZExtValue();
8075       int EndIdx =
8076           BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8077       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8078         BroadcastIdx -= BeginIdx;
8079         V = VInner;
8080       } else {
8081         V = VOuter;
8082       }
8083       continue;
8084     }
8085     }
8086     break;
8087   }
8088
8089   // Check if this is a broadcast of a scalar. We special case lowering
8090   // for scalars so that we can more effectively fold with loads.
8091   // First, look through bitcast: if the original value has a larger element
8092   // type than the shuffle, the broadcast element is in essence truncated.
8093   // Make that explicit to ease folding.
8094   if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8095     if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8096             DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8097       return TruncBroadcast;
8098
8099   // Also check the simpler case, where we can directly reuse the scalar.
8100   if (V.getOpcode() == ISD::BUILD_VECTOR ||
8101       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8102     V = V.getOperand(BroadcastIdx);
8103
8104     // If the scalar isn't a load, we can't broadcast from it in AVX1.
8105     // Only AVX2 has register broadcasts.
8106     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8107       return SDValue();
8108   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8109     // We can't broadcast from a vector register without AVX2, and we can only
8110     // broadcast from the zero-element of a vector register.
8111     return SDValue();
8112   }
8113
8114   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8115 }
8116
8117 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8118 // INSERTPS when the V1 elements are already in the correct locations
8119 // because otherwise we can just always use two SHUFPS instructions which
8120 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8121 // perform INSERTPS if a single V1 element is out of place and all V2
8122 // elements are zeroable.
8123 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8124                                             ArrayRef<int> Mask,
8125                                             SelectionDAG &DAG) {
8126   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8127   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8128   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8129   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8130
8131   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8132
8133   unsigned ZMask = 0;
8134   int V1DstIndex = -1;
8135   int V2DstIndex = -1;
8136   bool V1UsedInPlace = false;
8137
8138   for (int i = 0; i < 4; ++i) {
8139     // Synthesize a zero mask from the zeroable elements (includes undefs).
8140     if (Zeroable[i]) {
8141       ZMask |= 1 << i;
8142       continue;
8143     }
8144
8145     // Flag if we use any V1 inputs in place.
8146     if (i == Mask[i]) {
8147       V1UsedInPlace = true;
8148       continue;
8149     }
8150
8151     // We can only insert a single non-zeroable element.
8152     if (V1DstIndex != -1 || V2DstIndex != -1)
8153       return SDValue();
8154
8155     if (Mask[i] < 4) {
8156       // V1 input out of place for insertion.
8157       V1DstIndex = i;
8158     } else {
8159       // V2 input for insertion.
8160       V2DstIndex = i;
8161     }
8162   }
8163
8164   // Don't bother if we have no (non-zeroable) element for insertion.
8165   if (V1DstIndex == -1 && V2DstIndex == -1)
8166     return SDValue();
8167
8168   // Determine element insertion src/dst indices. The src index is from the
8169   // start of the inserted vector, not the start of the concatenated vector.
8170   unsigned V2SrcIndex = 0;
8171   if (V1DstIndex != -1) {
8172     // If we have a V1 input out of place, we use V1 as the V2 element insertion
8173     // and don't use the original V2 at all.
8174     V2SrcIndex = Mask[V1DstIndex];
8175     V2DstIndex = V1DstIndex;
8176     V2 = V1;
8177   } else {
8178     V2SrcIndex = Mask[V2DstIndex] - 4;
8179   }
8180
8181   // If no V1 inputs are used in place, then the result is created only from
8182   // the zero mask and the V2 insertion - so remove V1 dependency.
8183   if (!V1UsedInPlace)
8184     V1 = DAG.getUNDEF(MVT::v4f32);
8185
8186   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8187   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8188
8189   // Insert the V2 element into the desired position.
8190   SDLoc DL(Op);
8191   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8192                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
8193 }
8194
8195 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8196 /// UNPCK instruction.
8197 ///
8198 /// This specifically targets cases where we end up with alternating between
8199 /// the two inputs, and so can permute them into something that feeds a single
8200 /// UNPCK instruction. Note that this routine only targets integer vectors
8201 /// because for floating point vectors we have a generalized SHUFPS lowering
8202 /// strategy that handles everything that doesn't *exactly* match an unpack,
8203 /// making this clever lowering unnecessary.
8204 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8205                                                     SDValue V1, SDValue V2,
8206                                                     ArrayRef<int> Mask,
8207                                                     SelectionDAG &DAG) {
8208   assert(!VT.isFloatingPoint() &&
8209          "This routine only supports integer vectors.");
8210   assert(!isSingleInputShuffleMask(Mask) &&
8211          "This routine should only be used when blending two inputs.");
8212   assert(Mask.size() >= 2 && "Single element masks are invalid.");
8213
8214   int Size = Mask.size();
8215
8216   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8217     return M >= 0 && M % Size < Size / 2;
8218   });
8219   int NumHiInputs = std::count_if(
8220       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8221
8222   bool UnpackLo = NumLoInputs >= NumHiInputs;
8223
8224   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8225     SmallVector<int, 32> V1Mask(Mask.size(), -1);
8226     SmallVector<int, 32> V2Mask(Mask.size(), -1);
8227
8228     for (int i = 0; i < Size; ++i) {
8229       if (Mask[i] < 0)
8230         continue;
8231
8232       // Each element of the unpack contains Scale elements from this mask.
8233       int UnpackIdx = i / Scale;
8234
8235       // We only handle the case where V1 feeds the first slots of the unpack.
8236       // We rely on canonicalization to ensure this is the case.
8237       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8238         return SDValue();
8239
8240       // Setup the mask for this input. The indexing is tricky as we have to
8241       // handle the unpack stride.
8242       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8243       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8244           Mask[i] % Size;
8245     }
8246
8247     // If we will have to shuffle both inputs to use the unpack, check whether
8248     // we can just unpack first and shuffle the result. If so, skip this unpack.
8249     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8250         !isNoopShuffleMask(V2Mask))
8251       return SDValue();
8252
8253     // Shuffle the inputs into place.
8254     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8255     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8256
8257     // Cast the inputs to the type we will use to unpack them.
8258     V1 = DAG.getBitcast(UnpackVT, V1);
8259     V2 = DAG.getBitcast(UnpackVT, V2);
8260
8261     // Unpack the inputs and cast the result back to the desired type.
8262     return DAG.getBitcast(
8263         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8264                         UnpackVT, V1, V2));
8265   };
8266
8267   // We try each unpack from the largest to the smallest to try and find one
8268   // that fits this mask.
8269   int OrigNumElements = VT.getVectorNumElements();
8270   int OrigScalarSize = VT.getScalarSizeInBits();
8271   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8272     int Scale = ScalarSize / OrigScalarSize;
8273     int NumElements = OrigNumElements / Scale;
8274     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8275     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8276       return Unpack;
8277   }
8278
8279   // If none of the unpack-rooted lowerings worked (or were profitable) try an
8280   // initial unpack.
8281   if (NumLoInputs == 0 || NumHiInputs == 0) {
8282     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8283            "We have to have *some* inputs!");
8284     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8285
8286     // FIXME: We could consider the total complexity of the permute of each
8287     // possible unpacking. Or at the least we should consider how many
8288     // half-crossings are created.
8289     // FIXME: We could consider commuting the unpacks.
8290
8291     SmallVector<int, 32> PermMask;
8292     PermMask.assign(Size, -1);
8293     for (int i = 0; i < Size; ++i) {
8294       if (Mask[i] < 0)
8295         continue;
8296
8297       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8298
8299       PermMask[i] =
8300           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8301     }
8302     return DAG.getVectorShuffle(
8303         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8304                             DL, VT, V1, V2),
8305         DAG.getUNDEF(VT), PermMask);
8306   }
8307
8308   return SDValue();
8309 }
8310
8311 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8312 ///
8313 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8314 /// support for floating point shuffles but not integer shuffles. These
8315 /// instructions will incur a domain crossing penalty on some chips though so
8316 /// it is better to avoid lowering through this for integer vectors where
8317 /// possible.
8318 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8319                                        const X86Subtarget *Subtarget,
8320                                        SelectionDAG &DAG) {
8321   SDLoc DL(Op);
8322   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8323   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8324   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8325   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8326   ArrayRef<int> Mask = SVOp->getMask();
8327   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8328
8329   if (isSingleInputShuffleMask(Mask)) {
8330     // Use low duplicate instructions for masks that match their pattern.
8331     if (Subtarget->hasSSE3())
8332       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8333         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8334
8335     // Straight shuffle of a single input vector. Simulate this by using the
8336     // single input as both of the "inputs" to this instruction..
8337     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8338
8339     if (Subtarget->hasAVX()) {
8340       // If we have AVX, we can use VPERMILPS which will allow folding a load
8341       // into the shuffle.
8342       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8343                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8344     }
8345
8346     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8347                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8348   }
8349   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8350   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8351
8352   // If we have a single input, insert that into V1 if we can do so cheaply.
8353   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8354     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8355             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8356       return Insertion;
8357     // Try inverting the insertion since for v2 masks it is easy to do and we
8358     // can't reliably sort the mask one way or the other.
8359     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8360                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8361     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8362             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8363       return Insertion;
8364   }
8365
8366   // Try to use one of the special instruction patterns to handle two common
8367   // blend patterns if a zero-blend above didn't work.
8368   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8369       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8370     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8371       // We can either use a special instruction to load over the low double or
8372       // to move just the low double.
8373       return DAG.getNode(
8374           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8375           DL, MVT::v2f64, V2,
8376           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8377
8378   if (Subtarget->hasSSE41())
8379     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8380                                                   Subtarget, DAG))
8381       return Blend;
8382
8383   // Use dedicated unpack instructions for masks that match their pattern.
8384   if (SDValue V =
8385           lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8386     return V;
8387
8388   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8389   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8390                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8391 }
8392
8393 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8394 ///
8395 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8396 /// the integer unit to minimize domain crossing penalties. However, for blends
8397 /// it falls back to the floating point shuffle operation with appropriate bit
8398 /// casting.
8399 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8400                                        const X86Subtarget *Subtarget,
8401                                        SelectionDAG &DAG) {
8402   SDLoc DL(Op);
8403   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8404   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8405   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8406   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8407   ArrayRef<int> Mask = SVOp->getMask();
8408   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8409
8410   if (isSingleInputShuffleMask(Mask)) {
8411     // Check for being able to broadcast a single element.
8412     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8413                                                           Mask, Subtarget, DAG))
8414       return Broadcast;
8415
8416     // Straight shuffle of a single input vector. For everything from SSE2
8417     // onward this has a single fast instruction with no scary immediates.
8418     // We have to map the mask as it is actually a v4i32 shuffle instruction.
8419     V1 = DAG.getBitcast(MVT::v4i32, V1);
8420     int WidenedMask[4] = {
8421         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8422         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8423     return DAG.getBitcast(
8424         MVT::v2i64,
8425         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8426                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8427   }
8428   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8429   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8430   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8431   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8432
8433   // If we have a blend of two PACKUS operations an the blend aligns with the
8434   // low and half halves, we can just merge the PACKUS operations. This is
8435   // particularly important as it lets us merge shuffles that this routine itself
8436   // creates.
8437   auto GetPackNode = [](SDValue V) {
8438     while (V.getOpcode() == ISD::BITCAST)
8439       V = V.getOperand(0);
8440
8441     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8442   };
8443   if (SDValue V1Pack = GetPackNode(V1))
8444     if (SDValue V2Pack = GetPackNode(V2))
8445       return DAG.getBitcast(MVT::v2i64,
8446                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8447                                         Mask[0] == 0 ? V1Pack.getOperand(0)
8448                                                      : V1Pack.getOperand(1),
8449                                         Mask[1] == 2 ? V2Pack.getOperand(0)
8450                                                      : V2Pack.getOperand(1)));
8451
8452   // Try to use shift instructions.
8453   if (SDValue Shift =
8454           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8455     return Shift;
8456
8457   // When loading a scalar and then shuffling it into a vector we can often do
8458   // the insertion cheaply.
8459   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8460           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8461     return Insertion;
8462   // Try inverting the insertion since for v2 masks it is easy to do and we
8463   // can't reliably sort the mask one way or the other.
8464   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8465   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8466           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8467     return Insertion;
8468
8469   // We have different paths for blend lowering, but they all must use the
8470   // *exact* same predicate.
8471   bool IsBlendSupported = Subtarget->hasSSE41();
8472   if (IsBlendSupported)
8473     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8474                                                   Subtarget, DAG))
8475       return Blend;
8476
8477   // Use dedicated unpack instructions for masks that match their pattern.
8478   if (SDValue V =
8479           lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8480     return V;
8481
8482   // Try to use byte rotation instructions.
8483   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8484   if (Subtarget->hasSSSE3())
8485     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8486             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8487       return Rotate;
8488
8489   // If we have direct support for blends, we should lower by decomposing into
8490   // a permute. That will be faster than the domain cross.
8491   if (IsBlendSupported)
8492     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8493                                                       Mask, DAG);
8494
8495   // We implement this with SHUFPD which is pretty lame because it will likely
8496   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8497   // However, all the alternatives are still more cycles and newer chips don't
8498   // have this problem. It would be really nice if x86 had better shuffles here.
8499   V1 = DAG.getBitcast(MVT::v2f64, V1);
8500   V2 = DAG.getBitcast(MVT::v2f64, V2);
8501   return DAG.getBitcast(MVT::v2i64,
8502                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8503 }
8504
8505 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8506 ///
8507 /// This is used to disable more specialized lowerings when the shufps lowering
8508 /// will happen to be efficient.
8509 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8510   // This routine only handles 128-bit shufps.
8511   assert(Mask.size() == 4 && "Unsupported mask size!");
8512
8513   // To lower with a single SHUFPS we need to have the low half and high half
8514   // each requiring a single input.
8515   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8516     return false;
8517   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8518     return false;
8519
8520   return true;
8521 }
8522
8523 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8524 ///
8525 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8526 /// It makes no assumptions about whether this is the *best* lowering, it simply
8527 /// uses it.
8528 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8529                                             ArrayRef<int> Mask, SDValue V1,
8530                                             SDValue V2, SelectionDAG &DAG) {
8531   SDValue LowV = V1, HighV = V2;
8532   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8533
8534   int NumV2Elements =
8535       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8536
8537   if (NumV2Elements == 1) {
8538     int V2Index =
8539         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8540         Mask.begin();
8541
8542     // Compute the index adjacent to V2Index and in the same half by toggling
8543     // the low bit.
8544     int V2AdjIndex = V2Index ^ 1;
8545
8546     if (Mask[V2AdjIndex] == -1) {
8547       // Handles all the cases where we have a single V2 element and an undef.
8548       // This will only ever happen in the high lanes because we commute the
8549       // vector otherwise.
8550       if (V2Index < 2)
8551         std::swap(LowV, HighV);
8552       NewMask[V2Index] -= 4;
8553     } else {
8554       // Handle the case where the V2 element ends up adjacent to a V1 element.
8555       // To make this work, blend them together as the first step.
8556       int V1Index = V2AdjIndex;
8557       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8558       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8559                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8560
8561       // Now proceed to reconstruct the final blend as we have the necessary
8562       // high or low half formed.
8563       if (V2Index < 2) {
8564         LowV = V2;
8565         HighV = V1;
8566       } else {
8567         HighV = V2;
8568       }
8569       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8570       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8571     }
8572   } else if (NumV2Elements == 2) {
8573     if (Mask[0] < 4 && Mask[1] < 4) {
8574       // Handle the easy case where we have V1 in the low lanes and V2 in the
8575       // high lanes.
8576       NewMask[2] -= 4;
8577       NewMask[3] -= 4;
8578     } else if (Mask[2] < 4 && Mask[3] < 4) {
8579       // We also handle the reversed case because this utility may get called
8580       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8581       // arrange things in the right direction.
8582       NewMask[0] -= 4;
8583       NewMask[1] -= 4;
8584       HighV = V1;
8585       LowV = V2;
8586     } else {
8587       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8588       // trying to place elements directly, just blend them and set up the final
8589       // shuffle to place them.
8590
8591       // The first two blend mask elements are for V1, the second two are for
8592       // V2.
8593       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8594                           Mask[2] < 4 ? Mask[2] : Mask[3],
8595                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8596                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8597       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8598                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8599
8600       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8601       // a blend.
8602       LowV = HighV = V1;
8603       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8604       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8605       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8606       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8607     }
8608   }
8609   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8610                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8611 }
8612
8613 /// \brief Lower 4-lane 32-bit floating point shuffles.
8614 ///
8615 /// Uses instructions exclusively from the floating point unit to minimize
8616 /// domain crossing penalties, as these are sufficient to implement all v4f32
8617 /// shuffles.
8618 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8619                                        const X86Subtarget *Subtarget,
8620                                        SelectionDAG &DAG) {
8621   SDLoc DL(Op);
8622   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8623   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8624   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8625   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8626   ArrayRef<int> Mask = SVOp->getMask();
8627   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8628
8629   int NumV2Elements =
8630       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8631
8632   if (NumV2Elements == 0) {
8633     // Check for being able to broadcast a single element.
8634     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8635                                                           Mask, Subtarget, DAG))
8636       return Broadcast;
8637
8638     // Use even/odd duplicate instructions for masks that match their pattern.
8639     if (Subtarget->hasSSE3()) {
8640       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8641         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8642       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8643         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8644     }
8645
8646     if (Subtarget->hasAVX()) {
8647       // If we have AVX, we can use VPERMILPS which will allow folding a load
8648       // into the shuffle.
8649       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8650                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8651     }
8652
8653     // Otherwise, use a straight shuffle of a single input vector. We pass the
8654     // input vector to both operands to simulate this with a SHUFPS.
8655     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8656                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8657   }
8658
8659   // There are special ways we can lower some single-element blends. However, we
8660   // have custom ways we can lower more complex single-element blends below that
8661   // we defer to if both this and BLENDPS fail to match, so restrict this to
8662   // when the V2 input is targeting element 0 of the mask -- that is the fast
8663   // case here.
8664   if (NumV2Elements == 1 && Mask[0] >= 4)
8665     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8666                                                          Mask, Subtarget, DAG))
8667       return V;
8668
8669   if (Subtarget->hasSSE41()) {
8670     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8671                                                   Subtarget, DAG))
8672       return Blend;
8673
8674     // Use INSERTPS if we can complete the shuffle efficiently.
8675     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8676       return V;
8677
8678     if (!isSingleSHUFPSMask(Mask))
8679       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8680               DL, MVT::v4f32, V1, V2, Mask, DAG))
8681         return BlendPerm;
8682   }
8683
8684   // Use dedicated unpack instructions for masks that match their pattern.
8685   if (SDValue V =
8686           lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8687     return V;
8688
8689   // Otherwise fall back to a SHUFPS lowering strategy.
8690   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8691 }
8692
8693 /// \brief Lower 4-lane i32 vector shuffles.
8694 ///
8695 /// We try to handle these with integer-domain shuffles where we can, but for
8696 /// blends we use the floating point domain blend instructions.
8697 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8698                                        const X86Subtarget *Subtarget,
8699                                        SelectionDAG &DAG) {
8700   SDLoc DL(Op);
8701   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8702   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8703   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8704   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8705   ArrayRef<int> Mask = SVOp->getMask();
8706   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8707
8708   // Whenever we can lower this as a zext, that instruction is strictly faster
8709   // than any alternative. It also allows us to fold memory operands into the
8710   // shuffle in many cases.
8711   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8712                                                          Mask, Subtarget, DAG))
8713     return ZExt;
8714
8715   int NumV2Elements =
8716       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8717
8718   if (NumV2Elements == 0) {
8719     // Check for being able to broadcast a single element.
8720     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8721                                                           Mask, Subtarget, DAG))
8722       return Broadcast;
8723
8724     // Straight shuffle of a single input vector. For everything from SSE2
8725     // onward this has a single fast instruction with no scary immediates.
8726     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8727     // but we aren't actually going to use the UNPCK instruction because doing
8728     // so prevents folding a load into this instruction or making a copy.
8729     const int UnpackLoMask[] = {0, 0, 1, 1};
8730     const int UnpackHiMask[] = {2, 2, 3, 3};
8731     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8732       Mask = UnpackLoMask;
8733     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8734       Mask = UnpackHiMask;
8735
8736     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8737                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8738   }
8739
8740   // Try to use shift instructions.
8741   if (SDValue Shift =
8742           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8743     return Shift;
8744
8745   // There are special ways we can lower some single-element blends.
8746   if (NumV2Elements == 1)
8747     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8748                                                          Mask, Subtarget, DAG))
8749       return V;
8750
8751   // We have different paths for blend lowering, but they all must use the
8752   // *exact* same predicate.
8753   bool IsBlendSupported = Subtarget->hasSSE41();
8754   if (IsBlendSupported)
8755     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8756                                                   Subtarget, DAG))
8757       return Blend;
8758
8759   if (SDValue Masked =
8760           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8761     return Masked;
8762
8763   // Use dedicated unpack instructions for masks that match their pattern.
8764   if (SDValue V =
8765           lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8766     return V;
8767
8768   // Try to use byte rotation instructions.
8769   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8770   if (Subtarget->hasSSSE3())
8771     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8772             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8773       return Rotate;
8774
8775   // If we have direct support for blends, we should lower by decomposing into
8776   // a permute. That will be faster than the domain cross.
8777   if (IsBlendSupported)
8778     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8779                                                       Mask, DAG);
8780
8781   // Try to lower by permuting the inputs into an unpack instruction.
8782   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8783                                                             V2, Mask, DAG))
8784     return Unpack;
8785
8786   // We implement this with SHUFPS because it can blend from two vectors.
8787   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8788   // up the inputs, bypassing domain shift penalties that we would encur if we
8789   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8790   // relevant.
8791   return DAG.getBitcast(
8792       MVT::v4i32,
8793       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8794                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8795 }
8796
8797 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8798 /// shuffle lowering, and the most complex part.
8799 ///
8800 /// The lowering strategy is to try to form pairs of input lanes which are
8801 /// targeted at the same half of the final vector, and then use a dword shuffle
8802 /// to place them onto the right half, and finally unpack the paired lanes into
8803 /// their final position.
8804 ///
8805 /// The exact breakdown of how to form these dword pairs and align them on the
8806 /// correct sides is really tricky. See the comments within the function for
8807 /// more of the details.
8808 ///
8809 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8810 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8811 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8812 /// vector, form the analogous 128-bit 8-element Mask.
8813 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8814     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8815     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8816   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8817   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8818
8819   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8820   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8821   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8822
8823   SmallVector<int, 4> LoInputs;
8824   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8825                [](int M) { return M >= 0; });
8826   std::sort(LoInputs.begin(), LoInputs.end());
8827   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8828   SmallVector<int, 4> HiInputs;
8829   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8830                [](int M) { return M >= 0; });
8831   std::sort(HiInputs.begin(), HiInputs.end());
8832   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8833   int NumLToL =
8834       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8835   int NumHToL = LoInputs.size() - NumLToL;
8836   int NumLToH =
8837       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8838   int NumHToH = HiInputs.size() - NumLToH;
8839   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8840   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8841   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8842   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8843
8844   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8845   // such inputs we can swap two of the dwords across the half mark and end up
8846   // with <=2 inputs to each half in each half. Once there, we can fall through
8847   // to the generic code below. For example:
8848   //
8849   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8850   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8851   //
8852   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8853   // and an existing 2-into-2 on the other half. In this case we may have to
8854   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8855   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8856   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8857   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8858   // half than the one we target for fixing) will be fixed when we re-enter this
8859   // path. We will also combine away any sequence of PSHUFD instructions that
8860   // result into a single instruction. Here is an example of the tricky case:
8861   //
8862   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8863   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8864   //
8865   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8866   //
8867   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8868   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8869   //
8870   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8871   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8872   //
8873   // The result is fine to be handled by the generic logic.
8874   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8875                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8876                           int AOffset, int BOffset) {
8877     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8878            "Must call this with A having 3 or 1 inputs from the A half.");
8879     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8880            "Must call this with B having 1 or 3 inputs from the B half.");
8881     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8882            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8883
8884     bool ThreeAInputs = AToAInputs.size() == 3;
8885
8886     // Compute the index of dword with only one word among the three inputs in
8887     // a half by taking the sum of the half with three inputs and subtracting
8888     // the sum of the actual three inputs. The difference is the remaining
8889     // slot.
8890     int ADWord, BDWord;
8891     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8892     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8893     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8894     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8895     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8896     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8897     int TripleNonInputIdx =
8898         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8899     TripleDWord = TripleNonInputIdx / 2;
8900
8901     // We use xor with one to compute the adjacent DWord to whichever one the
8902     // OneInput is in.
8903     OneInputDWord = (OneInput / 2) ^ 1;
8904
8905     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8906     // and BToA inputs. If there is also such a problem with the BToB and AToB
8907     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8908     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8909     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8910     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8911       // Compute how many inputs will be flipped by swapping these DWords. We
8912       // need
8913       // to balance this to ensure we don't form a 3-1 shuffle in the other
8914       // half.
8915       int NumFlippedAToBInputs =
8916           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8917           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8918       int NumFlippedBToBInputs =
8919           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8920           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8921       if ((NumFlippedAToBInputs == 1 &&
8922            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8923           (NumFlippedBToBInputs == 1 &&
8924            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8925         // We choose whether to fix the A half or B half based on whether that
8926         // half has zero flipped inputs. At zero, we may not be able to fix it
8927         // with that half. We also bias towards fixing the B half because that
8928         // will more commonly be the high half, and we have to bias one way.
8929         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8930                                                        ArrayRef<int> Inputs) {
8931           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8932           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8933                                          PinnedIdx ^ 1) != Inputs.end();
8934           // Determine whether the free index is in the flipped dword or the
8935           // unflipped dword based on where the pinned index is. We use this bit
8936           // in an xor to conditionally select the adjacent dword.
8937           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8938           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8939                                              FixFreeIdx) != Inputs.end();
8940           if (IsFixIdxInput == IsFixFreeIdxInput)
8941             FixFreeIdx += 1;
8942           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8943                                         FixFreeIdx) != Inputs.end();
8944           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8945                  "We need to be changing the number of flipped inputs!");
8946           int PSHUFHalfMask[] = {0, 1, 2, 3};
8947           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8948           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8949                           MVT::v8i16, V,
8950                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8951
8952           for (int &M : Mask)
8953             if (M != -1 && M == FixIdx)
8954               M = FixFreeIdx;
8955             else if (M != -1 && M == FixFreeIdx)
8956               M = FixIdx;
8957         };
8958         if (NumFlippedBToBInputs != 0) {
8959           int BPinnedIdx =
8960               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8961           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8962         } else {
8963           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8964           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8965           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8966         }
8967       }
8968     }
8969
8970     int PSHUFDMask[] = {0, 1, 2, 3};
8971     PSHUFDMask[ADWord] = BDWord;
8972     PSHUFDMask[BDWord] = ADWord;
8973     V = DAG.getBitcast(
8974         VT,
8975         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8976                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8977
8978     // Adjust the mask to match the new locations of A and B.
8979     for (int &M : Mask)
8980       if (M != -1 && M/2 == ADWord)
8981         M = 2 * BDWord + M % 2;
8982       else if (M != -1 && M/2 == BDWord)
8983         M = 2 * ADWord + M % 2;
8984
8985     // Recurse back into this routine to re-compute state now that this isn't
8986     // a 3 and 1 problem.
8987     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8988                                                      DAG);
8989   };
8990   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8991     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8992   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8993     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8994
8995   // At this point there are at most two inputs to the low and high halves from
8996   // each half. That means the inputs can always be grouped into dwords and
8997   // those dwords can then be moved to the correct half with a dword shuffle.
8998   // We use at most one low and one high word shuffle to collect these paired
8999   // inputs into dwords, and finally a dword shuffle to place them.
9000   int PSHUFLMask[4] = {-1, -1, -1, -1};
9001   int PSHUFHMask[4] = {-1, -1, -1, -1};
9002   int PSHUFDMask[4] = {-1, -1, -1, -1};
9003
9004   // First fix the masks for all the inputs that are staying in their
9005   // original halves. This will then dictate the targets of the cross-half
9006   // shuffles.
9007   auto fixInPlaceInputs =
9008       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9009                     MutableArrayRef<int> SourceHalfMask,
9010                     MutableArrayRef<int> HalfMask, int HalfOffset) {
9011     if (InPlaceInputs.empty())
9012       return;
9013     if (InPlaceInputs.size() == 1) {
9014       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9015           InPlaceInputs[0] - HalfOffset;
9016       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9017       return;
9018     }
9019     if (IncomingInputs.empty()) {
9020       // Just fix all of the in place inputs.
9021       for (int Input : InPlaceInputs) {
9022         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9023         PSHUFDMask[Input / 2] = Input / 2;
9024       }
9025       return;
9026     }
9027
9028     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9029     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9030         InPlaceInputs[0] - HalfOffset;
9031     // Put the second input next to the first so that they are packed into
9032     // a dword. We find the adjacent index by toggling the low bit.
9033     int AdjIndex = InPlaceInputs[0] ^ 1;
9034     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9035     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9036     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9037   };
9038   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9039   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9040
9041   // Now gather the cross-half inputs and place them into a free dword of
9042   // their target half.
9043   // FIXME: This operation could almost certainly be simplified dramatically to
9044   // look more like the 3-1 fixing operation.
9045   auto moveInputsToRightHalf = [&PSHUFDMask](
9046       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9047       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9048       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9049       int DestOffset) {
9050     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9051       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9052     };
9053     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9054                                                int Word) {
9055       int LowWord = Word & ~1;
9056       int HighWord = Word | 1;
9057       return isWordClobbered(SourceHalfMask, LowWord) ||
9058              isWordClobbered(SourceHalfMask, HighWord);
9059     };
9060
9061     if (IncomingInputs.empty())
9062       return;
9063
9064     if (ExistingInputs.empty()) {
9065       // Map any dwords with inputs from them into the right half.
9066       for (int Input : IncomingInputs) {
9067         // If the source half mask maps over the inputs, turn those into
9068         // swaps and use the swapped lane.
9069         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9070           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9071             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9072                 Input - SourceOffset;
9073             // We have to swap the uses in our half mask in one sweep.
9074             for (int &M : HalfMask)
9075               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9076                 M = Input;
9077               else if (M == Input)
9078                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9079           } else {
9080             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9081                        Input - SourceOffset &&
9082                    "Previous placement doesn't match!");
9083           }
9084           // Note that this correctly re-maps both when we do a swap and when
9085           // we observe the other side of the swap above. We rely on that to
9086           // avoid swapping the members of the input list directly.
9087           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9088         }
9089
9090         // Map the input's dword into the correct half.
9091         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9092           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9093         else
9094           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9095                      Input / 2 &&
9096                  "Previous placement doesn't match!");
9097       }
9098
9099       // And just directly shift any other-half mask elements to be same-half
9100       // as we will have mirrored the dword containing the element into the
9101       // same position within that half.
9102       for (int &M : HalfMask)
9103         if (M >= SourceOffset && M < SourceOffset + 4) {
9104           M = M - SourceOffset + DestOffset;
9105           assert(M >= 0 && "This should never wrap below zero!");
9106         }
9107       return;
9108     }
9109
9110     // Ensure we have the input in a viable dword of its current half. This
9111     // is particularly tricky because the original position may be clobbered
9112     // by inputs being moved and *staying* in that half.
9113     if (IncomingInputs.size() == 1) {
9114       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9115         int InputFixed = std::find(std::begin(SourceHalfMask),
9116                                    std::end(SourceHalfMask), -1) -
9117                          std::begin(SourceHalfMask) + SourceOffset;
9118         SourceHalfMask[InputFixed - SourceOffset] =
9119             IncomingInputs[0] - SourceOffset;
9120         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9121                      InputFixed);
9122         IncomingInputs[0] = InputFixed;
9123       }
9124     } else if (IncomingInputs.size() == 2) {
9125       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9126           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9127         // We have two non-adjacent or clobbered inputs we need to extract from
9128         // the source half. To do this, we need to map them into some adjacent
9129         // dword slot in the source mask.
9130         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9131                               IncomingInputs[1] - SourceOffset};
9132
9133         // If there is a free slot in the source half mask adjacent to one of
9134         // the inputs, place the other input in it. We use (Index XOR 1) to
9135         // compute an adjacent index.
9136         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9137             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9138           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9139           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9140           InputsFixed[1] = InputsFixed[0] ^ 1;
9141         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9142                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9143           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9144           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9145           InputsFixed[0] = InputsFixed[1] ^ 1;
9146         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9147                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9148           // The two inputs are in the same DWord but it is clobbered and the
9149           // adjacent DWord isn't used at all. Move both inputs to the free
9150           // slot.
9151           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9152           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9153           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9154           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9155         } else {
9156           // The only way we hit this point is if there is no clobbering
9157           // (because there are no off-half inputs to this half) and there is no
9158           // free slot adjacent to one of the inputs. In this case, we have to
9159           // swap an input with a non-input.
9160           for (int i = 0; i < 4; ++i)
9161             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9162                    "We can't handle any clobbers here!");
9163           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9164                  "Cannot have adjacent inputs here!");
9165
9166           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9167           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9168
9169           // We also have to update the final source mask in this case because
9170           // it may need to undo the above swap.
9171           for (int &M : FinalSourceHalfMask)
9172             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9173               M = InputsFixed[1] + SourceOffset;
9174             else if (M == InputsFixed[1] + SourceOffset)
9175               M = (InputsFixed[0] ^ 1) + SourceOffset;
9176
9177           InputsFixed[1] = InputsFixed[0] ^ 1;
9178         }
9179
9180         // Point everything at the fixed inputs.
9181         for (int &M : HalfMask)
9182           if (M == IncomingInputs[0])
9183             M = InputsFixed[0] + SourceOffset;
9184           else if (M == IncomingInputs[1])
9185             M = InputsFixed[1] + SourceOffset;
9186
9187         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9188         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9189       }
9190     } else {
9191       llvm_unreachable("Unhandled input size!");
9192     }
9193
9194     // Now hoist the DWord down to the right half.
9195     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9196     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9197     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9198     for (int &M : HalfMask)
9199       for (int Input : IncomingInputs)
9200         if (M == Input)
9201           M = FreeDWord * 2 + Input % 2;
9202   };
9203   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9204                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
9205   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9206                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
9207
9208   // Now enact all the shuffles we've computed to move the inputs into their
9209   // target half.
9210   if (!isNoopShuffleMask(PSHUFLMask))
9211     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9212                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9213   if (!isNoopShuffleMask(PSHUFHMask))
9214     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9215                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9216   if (!isNoopShuffleMask(PSHUFDMask))
9217     V = DAG.getBitcast(
9218         VT,
9219         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9220                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9221
9222   // At this point, each half should contain all its inputs, and we can then
9223   // just shuffle them into their final position.
9224   assert(std::count_if(LoMask.begin(), LoMask.end(),
9225                        [](int M) { return M >= 4; }) == 0 &&
9226          "Failed to lift all the high half inputs to the low mask!");
9227   assert(std::count_if(HiMask.begin(), HiMask.end(),
9228                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
9229          "Failed to lift all the low half inputs to the high mask!");
9230
9231   // Do a half shuffle for the low mask.
9232   if (!isNoopShuffleMask(LoMask))
9233     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9234                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9235
9236   // Do a half shuffle with the high mask after shifting its values down.
9237   for (int &M : HiMask)
9238     if (M >= 0)
9239       M -= 4;
9240   if (!isNoopShuffleMask(HiMask))
9241     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9242                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9243
9244   return V;
9245 }
9246
9247 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9248 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9249                                           SDValue V2, ArrayRef<int> Mask,
9250                                           SelectionDAG &DAG, bool &V1InUse,
9251                                           bool &V2InUse) {
9252   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9253   SDValue V1Mask[16];
9254   SDValue V2Mask[16];
9255   V1InUse = false;
9256   V2InUse = false;
9257
9258   int Size = Mask.size();
9259   int Scale = 16 / Size;
9260   for (int i = 0; i < 16; ++i) {
9261     if (Mask[i / Scale] == -1) {
9262       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9263     } else {
9264       const int ZeroMask = 0x80;
9265       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9266                                           : ZeroMask;
9267       int V2Idx = Mask[i / Scale] < Size
9268                       ? ZeroMask
9269                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
9270       if (Zeroable[i / Scale])
9271         V1Idx = V2Idx = ZeroMask;
9272       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9273       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9274       V1InUse |= (ZeroMask != V1Idx);
9275       V2InUse |= (ZeroMask != V2Idx);
9276     }
9277   }
9278
9279   if (V1InUse)
9280     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9281                      DAG.getBitcast(MVT::v16i8, V1),
9282                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9283   if (V2InUse)
9284     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9285                      DAG.getBitcast(MVT::v16i8, V2),
9286                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9287
9288   // If we need shuffled inputs from both, blend the two.
9289   SDValue V;
9290   if (V1InUse && V2InUse)
9291     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9292   else
9293     V = V1InUse ? V1 : V2;
9294
9295   // Cast the result back to the correct type.
9296   return DAG.getBitcast(VT, V);
9297 }
9298
9299 /// \brief Generic lowering of 8-lane i16 shuffles.
9300 ///
9301 /// This handles both single-input shuffles and combined shuffle/blends with
9302 /// two inputs. The single input shuffles are immediately delegated to
9303 /// a dedicated lowering routine.
9304 ///
9305 /// The blends are lowered in one of three fundamental ways. If there are few
9306 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9307 /// of the input is significantly cheaper when lowered as an interleaving of
9308 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9309 /// halves of the inputs separately (making them have relatively few inputs)
9310 /// and then concatenate them.
9311 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9312                                        const X86Subtarget *Subtarget,
9313                                        SelectionDAG &DAG) {
9314   SDLoc DL(Op);
9315   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9316   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9317   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9318   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9319   ArrayRef<int> OrigMask = SVOp->getMask();
9320   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9321                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9322   MutableArrayRef<int> Mask(MaskStorage);
9323
9324   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9325
9326   // Whenever we can lower this as a zext, that instruction is strictly faster
9327   // than any alternative.
9328   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9329           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9330     return ZExt;
9331
9332   auto isV1 = [](int M) { return M >= 0 && M < 8; };
9333   (void)isV1;
9334   auto isV2 = [](int M) { return M >= 8; };
9335
9336   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9337
9338   if (NumV2Inputs == 0) {
9339     // Check for being able to broadcast a single element.
9340     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9341                                                           Mask, Subtarget, DAG))
9342       return Broadcast;
9343
9344     // Try to use shift instructions.
9345     if (SDValue Shift =
9346             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9347       return Shift;
9348
9349     // Use dedicated unpack instructions for masks that match their pattern.
9350     if (SDValue V =
9351             lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9352       return V;
9353
9354     // Try to use byte rotation instructions.
9355     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9356                                                         Mask, Subtarget, DAG))
9357       return Rotate;
9358
9359     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9360                                                      Subtarget, DAG);
9361   }
9362
9363   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9364          "All single-input shuffles should be canonicalized to be V1-input "
9365          "shuffles.");
9366
9367   // Try to use shift instructions.
9368   if (SDValue Shift =
9369           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9370     return Shift;
9371
9372   // See if we can use SSE4A Extraction / Insertion.
9373   if (Subtarget->hasSSE4A())
9374     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9375       return V;
9376
9377   // There are special ways we can lower some single-element blends.
9378   if (NumV2Inputs == 1)
9379     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9380                                                          Mask, Subtarget, DAG))
9381       return V;
9382
9383   // We have different paths for blend lowering, but they all must use the
9384   // *exact* same predicate.
9385   bool IsBlendSupported = Subtarget->hasSSE41();
9386   if (IsBlendSupported)
9387     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9388                                                   Subtarget, DAG))
9389       return Blend;
9390
9391   if (SDValue Masked =
9392           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9393     return Masked;
9394
9395   // Use dedicated unpack instructions for masks that match their pattern.
9396   if (SDValue V =
9397           lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9398     return V;
9399
9400   // Try to use byte rotation instructions.
9401   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9402           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9403     return Rotate;
9404
9405   if (SDValue BitBlend =
9406           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9407     return BitBlend;
9408
9409   if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9410                                                             V2, Mask, DAG))
9411     return Unpack;
9412
9413   // If we can't directly blend but can use PSHUFB, that will be better as it
9414   // can both shuffle and set up the inefficient blend.
9415   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9416     bool V1InUse, V2InUse;
9417     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9418                                       V1InUse, V2InUse);
9419   }
9420
9421   // We can always bit-blend if we have to so the fallback strategy is to
9422   // decompose into single-input permutes and blends.
9423   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9424                                                       Mask, DAG);
9425 }
9426
9427 /// \brief Check whether a compaction lowering can be done by dropping even
9428 /// elements and compute how many times even elements must be dropped.
9429 ///
9430 /// This handles shuffles which take every Nth element where N is a power of
9431 /// two. Example shuffle masks:
9432 ///
9433 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
9434 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9435 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
9436 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
9437 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
9438 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
9439 ///
9440 /// Any of these lanes can of course be undef.
9441 ///
9442 /// This routine only supports N <= 3.
9443 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9444 /// for larger N.
9445 ///
9446 /// \returns N above, or the number of times even elements must be dropped if
9447 /// there is such a number. Otherwise returns zero.
9448 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9449   // Figure out whether we're looping over two inputs or just one.
9450   bool IsSingleInput = isSingleInputShuffleMask(Mask);
9451
9452   // The modulus for the shuffle vector entries is based on whether this is
9453   // a single input or not.
9454   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9455   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9456          "We should only be called with masks with a power-of-2 size!");
9457
9458   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9459
9460   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9461   // and 2^3 simultaneously. This is because we may have ambiguity with
9462   // partially undef inputs.
9463   bool ViableForN[3] = {true, true, true};
9464
9465   for (int i = 0, e = Mask.size(); i < e; ++i) {
9466     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9467     // want.
9468     if (Mask[i] == -1)
9469       continue;
9470
9471     bool IsAnyViable = false;
9472     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9473       if (ViableForN[j]) {
9474         uint64_t N = j + 1;
9475
9476         // The shuffle mask must be equal to (i * 2^N) % M.
9477         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9478           IsAnyViable = true;
9479         else
9480           ViableForN[j] = false;
9481       }
9482     // Early exit if we exhaust the possible powers of two.
9483     if (!IsAnyViable)
9484       break;
9485   }
9486
9487   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9488     if (ViableForN[j])
9489       return j + 1;
9490
9491   // Return 0 as there is no viable power of two.
9492   return 0;
9493 }
9494
9495 /// \brief Generic lowering of v16i8 shuffles.
9496 ///
9497 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9498 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9499 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9500 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9501 /// back together.
9502 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9503                                        const X86Subtarget *Subtarget,
9504                                        SelectionDAG &DAG) {
9505   SDLoc DL(Op);
9506   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9507   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9508   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9509   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9510   ArrayRef<int> Mask = SVOp->getMask();
9511   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9512
9513   // Try to use shift instructions.
9514   if (SDValue Shift =
9515           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9516     return Shift;
9517
9518   // Try to use byte rotation instructions.
9519   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9520           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9521     return Rotate;
9522
9523   // Try to use a zext lowering.
9524   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9525           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9526     return ZExt;
9527
9528   // See if we can use SSE4A Extraction / Insertion.
9529   if (Subtarget->hasSSE4A())
9530     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9531       return V;
9532
9533   int NumV2Elements =
9534       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9535
9536   // For single-input shuffles, there are some nicer lowering tricks we can use.
9537   if (NumV2Elements == 0) {
9538     // Check for being able to broadcast a single element.
9539     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9540                                                           Mask, Subtarget, DAG))
9541       return Broadcast;
9542
9543     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9544     // Notably, this handles splat and partial-splat shuffles more efficiently.
9545     // However, it only makes sense if the pre-duplication shuffle simplifies
9546     // things significantly. Currently, this means we need to be able to
9547     // express the pre-duplication shuffle as an i16 shuffle.
9548     //
9549     // FIXME: We should check for other patterns which can be widened into an
9550     // i16 shuffle as well.
9551     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9552       for (int i = 0; i < 16; i += 2)
9553         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9554           return false;
9555
9556       return true;
9557     };
9558     auto tryToWidenViaDuplication = [&]() -> SDValue {
9559       if (!canWidenViaDuplication(Mask))
9560         return SDValue();
9561       SmallVector<int, 4> LoInputs;
9562       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9563                    [](int M) { return M >= 0 && M < 8; });
9564       std::sort(LoInputs.begin(), LoInputs.end());
9565       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9566                      LoInputs.end());
9567       SmallVector<int, 4> HiInputs;
9568       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9569                    [](int M) { return M >= 8; });
9570       std::sort(HiInputs.begin(), HiInputs.end());
9571       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9572                      HiInputs.end());
9573
9574       bool TargetLo = LoInputs.size() >= HiInputs.size();
9575       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9576       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9577
9578       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9579       SmallDenseMap<int, int, 8> LaneMap;
9580       for (int I : InPlaceInputs) {
9581         PreDupI16Shuffle[I/2] = I/2;
9582         LaneMap[I] = I;
9583       }
9584       int j = TargetLo ? 0 : 4, je = j + 4;
9585       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9586         // Check if j is already a shuffle of this input. This happens when
9587         // there are two adjacent bytes after we move the low one.
9588         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9589           // If we haven't yet mapped the input, search for a slot into which
9590           // we can map it.
9591           while (j < je && PreDupI16Shuffle[j] != -1)
9592             ++j;
9593
9594           if (j == je)
9595             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9596             return SDValue();
9597
9598           // Map this input with the i16 shuffle.
9599           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9600         }
9601
9602         // Update the lane map based on the mapping we ended up with.
9603         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9604       }
9605       V1 = DAG.getBitcast(
9606           MVT::v16i8,
9607           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9608                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9609
9610       // Unpack the bytes to form the i16s that will be shuffled into place.
9611       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9612                        MVT::v16i8, V1, V1);
9613
9614       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9615       for (int i = 0; i < 16; ++i)
9616         if (Mask[i] != -1) {
9617           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9618           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9619           if (PostDupI16Shuffle[i / 2] == -1)
9620             PostDupI16Shuffle[i / 2] = MappedMask;
9621           else
9622             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9623                    "Conflicting entrties in the original shuffle!");
9624         }
9625       return DAG.getBitcast(
9626           MVT::v16i8,
9627           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9628                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9629     };
9630     if (SDValue V = tryToWidenViaDuplication())
9631       return V;
9632   }
9633
9634   if (SDValue Masked =
9635           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9636     return Masked;
9637
9638   // Use dedicated unpack instructions for masks that match their pattern.
9639   if (SDValue V =
9640           lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9641     return V;
9642
9643   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9644   // with PSHUFB. It is important to do this before we attempt to generate any
9645   // blends but after all of the single-input lowerings. If the single input
9646   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9647   // want to preserve that and we can DAG combine any longer sequences into
9648   // a PSHUFB in the end. But once we start blending from multiple inputs,
9649   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9650   // and there are *very* few patterns that would actually be faster than the
9651   // PSHUFB approach because of its ability to zero lanes.
9652   //
9653   // FIXME: The only exceptions to the above are blends which are exact
9654   // interleavings with direct instructions supporting them. We currently don't
9655   // handle those well here.
9656   if (Subtarget->hasSSSE3()) {
9657     bool V1InUse = false;
9658     bool V2InUse = false;
9659
9660     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9661                                                 DAG, V1InUse, V2InUse);
9662
9663     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9664     // do so. This avoids using them to handle blends-with-zero which is
9665     // important as a single pshufb is significantly faster for that.
9666     if (V1InUse && V2InUse) {
9667       if (Subtarget->hasSSE41())
9668         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9669                                                       Mask, Subtarget, DAG))
9670           return Blend;
9671
9672       // We can use an unpack to do the blending rather than an or in some
9673       // cases. Even though the or may be (very minorly) more efficient, we
9674       // preference this lowering because there are common cases where part of
9675       // the complexity of the shuffles goes away when we do the final blend as
9676       // an unpack.
9677       // FIXME: It might be worth trying to detect if the unpack-feeding
9678       // shuffles will both be pshufb, in which case we shouldn't bother with
9679       // this.
9680       if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9681               DL, MVT::v16i8, V1, V2, Mask, DAG))
9682         return Unpack;
9683     }
9684
9685     return PSHUFB;
9686   }
9687
9688   // There are special ways we can lower some single-element blends.
9689   if (NumV2Elements == 1)
9690     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9691                                                          Mask, Subtarget, DAG))
9692       return V;
9693
9694   if (SDValue BitBlend =
9695           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9696     return BitBlend;
9697
9698   // Check whether a compaction lowering can be done. This handles shuffles
9699   // which take every Nth element for some even N. See the helper function for
9700   // details.
9701   //
9702   // We special case these as they can be particularly efficiently handled with
9703   // the PACKUSB instruction on x86 and they show up in common patterns of
9704   // rearranging bytes to truncate wide elements.
9705   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9706     // NumEvenDrops is the power of two stride of the elements. Another way of
9707     // thinking about it is that we need to drop the even elements this many
9708     // times to get the original input.
9709     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9710
9711     // First we need to zero all the dropped bytes.
9712     assert(NumEvenDrops <= 3 &&
9713            "No support for dropping even elements more than 3 times.");
9714     // We use the mask type to pick which bytes are preserved based on how many
9715     // elements are dropped.
9716     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9717     SDValue ByteClearMask = DAG.getBitcast(
9718         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9719     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9720     if (!IsSingleInput)
9721       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9722
9723     // Now pack things back together.
9724     V1 = DAG.getBitcast(MVT::v8i16, V1);
9725     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9726     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9727     for (int i = 1; i < NumEvenDrops; ++i) {
9728       Result = DAG.getBitcast(MVT::v8i16, Result);
9729       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9730     }
9731
9732     return Result;
9733   }
9734
9735   // Handle multi-input cases by blending single-input shuffles.
9736   if (NumV2Elements > 0)
9737     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9738                                                       Mask, DAG);
9739
9740   // The fallback path for single-input shuffles widens this into two v8i16
9741   // vectors with unpacks, shuffles those, and then pulls them back together
9742   // with a pack.
9743   SDValue V = V1;
9744
9745   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9746   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9747   for (int i = 0; i < 16; ++i)
9748     if (Mask[i] >= 0)
9749       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9750
9751   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9752
9753   SDValue VLoHalf, VHiHalf;
9754   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9755   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9756   // i16s.
9757   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9758                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9759       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9760                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9761     // Use a mask to drop the high bytes.
9762     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9763     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9764                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9765
9766     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9767     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9768
9769     // Squash the masks to point directly into VLoHalf.
9770     for (int &M : LoBlendMask)
9771       if (M >= 0)
9772         M /= 2;
9773     for (int &M : HiBlendMask)
9774       if (M >= 0)
9775         M /= 2;
9776   } else {
9777     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9778     // VHiHalf so that we can blend them as i16s.
9779     VLoHalf = DAG.getBitcast(
9780         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9781     VHiHalf = DAG.getBitcast(
9782         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9783   }
9784
9785   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9786   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9787
9788   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9789 }
9790
9791 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9792 ///
9793 /// This routine breaks down the specific type of 128-bit shuffle and
9794 /// dispatches to the lowering routines accordingly.
9795 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9796                                         MVT VT, const X86Subtarget *Subtarget,
9797                                         SelectionDAG &DAG) {
9798   switch (VT.SimpleTy) {
9799   case MVT::v2i64:
9800     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9801   case MVT::v2f64:
9802     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9803   case MVT::v4i32:
9804     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9805   case MVT::v4f32:
9806     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9807   case MVT::v8i16:
9808     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9809   case MVT::v16i8:
9810     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9811
9812   default:
9813     llvm_unreachable("Unimplemented!");
9814   }
9815 }
9816
9817 /// \brief Helper function to test whether a shuffle mask could be
9818 /// simplified by widening the elements being shuffled.
9819 ///
9820 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9821 /// leaves it in an unspecified state.
9822 ///
9823 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9824 /// shuffle masks. The latter have the special property of a '-2' representing
9825 /// a zero-ed lane of a vector.
9826 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9827                                     SmallVectorImpl<int> &WidenedMask) {
9828   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9829     // If both elements are undef, its trivial.
9830     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9831       WidenedMask.push_back(SM_SentinelUndef);
9832       continue;
9833     }
9834
9835     // Check for an undef mask and a mask value properly aligned to fit with
9836     // a pair of values. If we find such a case, use the non-undef mask's value.
9837     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9838       WidenedMask.push_back(Mask[i + 1] / 2);
9839       continue;
9840     }
9841     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9842       WidenedMask.push_back(Mask[i] / 2);
9843       continue;
9844     }
9845
9846     // When zeroing, we need to spread the zeroing across both lanes to widen.
9847     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9848       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9849           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9850         WidenedMask.push_back(SM_SentinelZero);
9851         continue;
9852       }
9853       return false;
9854     }
9855
9856     // Finally check if the two mask values are adjacent and aligned with
9857     // a pair.
9858     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9859       WidenedMask.push_back(Mask[i] / 2);
9860       continue;
9861     }
9862
9863     // Otherwise we can't safely widen the elements used in this shuffle.
9864     return false;
9865   }
9866   assert(WidenedMask.size() == Mask.size() / 2 &&
9867          "Incorrect size of mask after widening the elements!");
9868
9869   return true;
9870 }
9871
9872 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9873 ///
9874 /// This routine just extracts two subvectors, shuffles them independently, and
9875 /// then concatenates them back together. This should work effectively with all
9876 /// AVX vector shuffle types.
9877 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9878                                           SDValue V2, ArrayRef<int> Mask,
9879                                           SelectionDAG &DAG) {
9880   assert(VT.getSizeInBits() >= 256 &&
9881          "Only for 256-bit or wider vector shuffles!");
9882   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9883   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9884
9885   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9886   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9887
9888   int NumElements = VT.getVectorNumElements();
9889   int SplitNumElements = NumElements / 2;
9890   MVT ScalarVT = VT.getVectorElementType();
9891   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9892
9893   // Rather than splitting build-vectors, just build two narrower build
9894   // vectors. This helps shuffling with splats and zeros.
9895   auto SplitVector = [&](SDValue V) {
9896     while (V.getOpcode() == ISD::BITCAST)
9897       V = V->getOperand(0);
9898
9899     MVT OrigVT = V.getSimpleValueType();
9900     int OrigNumElements = OrigVT.getVectorNumElements();
9901     int OrigSplitNumElements = OrigNumElements / 2;
9902     MVT OrigScalarVT = OrigVT.getVectorElementType();
9903     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9904
9905     SDValue LoV, HiV;
9906
9907     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9908     if (!BV) {
9909       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9910                         DAG.getIntPtrConstant(0, DL));
9911       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9912                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9913     } else {
9914
9915       SmallVector<SDValue, 16> LoOps, HiOps;
9916       for (int i = 0; i < OrigSplitNumElements; ++i) {
9917         LoOps.push_back(BV->getOperand(i));
9918         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9919       }
9920       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9921       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9922     }
9923     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9924                           DAG.getBitcast(SplitVT, HiV));
9925   };
9926
9927   SDValue LoV1, HiV1, LoV2, HiV2;
9928   std::tie(LoV1, HiV1) = SplitVector(V1);
9929   std::tie(LoV2, HiV2) = SplitVector(V2);
9930
9931   // Now create two 4-way blends of these half-width vectors.
9932   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9933     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9934     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9935     for (int i = 0; i < SplitNumElements; ++i) {
9936       int M = HalfMask[i];
9937       if (M >= NumElements) {
9938         if (M >= NumElements + SplitNumElements)
9939           UseHiV2 = true;
9940         else
9941           UseLoV2 = true;
9942         V2BlendMask.push_back(M - NumElements);
9943         V1BlendMask.push_back(-1);
9944         BlendMask.push_back(SplitNumElements + i);
9945       } else if (M >= 0) {
9946         if (M >= SplitNumElements)
9947           UseHiV1 = true;
9948         else
9949           UseLoV1 = true;
9950         V2BlendMask.push_back(-1);
9951         V1BlendMask.push_back(M);
9952         BlendMask.push_back(i);
9953       } else {
9954         V2BlendMask.push_back(-1);
9955         V1BlendMask.push_back(-1);
9956         BlendMask.push_back(-1);
9957       }
9958     }
9959
9960     // Because the lowering happens after all combining takes place, we need to
9961     // manually combine these blend masks as much as possible so that we create
9962     // a minimal number of high-level vector shuffle nodes.
9963
9964     // First try just blending the halves of V1 or V2.
9965     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9966       return DAG.getUNDEF(SplitVT);
9967     if (!UseLoV2 && !UseHiV2)
9968       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9969     if (!UseLoV1 && !UseHiV1)
9970       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9971
9972     SDValue V1Blend, V2Blend;
9973     if (UseLoV1 && UseHiV1) {
9974       V1Blend =
9975         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9976     } else {
9977       // We only use half of V1 so map the usage down into the final blend mask.
9978       V1Blend = UseLoV1 ? LoV1 : HiV1;
9979       for (int i = 0; i < SplitNumElements; ++i)
9980         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9981           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9982     }
9983     if (UseLoV2 && UseHiV2) {
9984       V2Blend =
9985         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9986     } else {
9987       // We only use half of V2 so map the usage down into the final blend mask.
9988       V2Blend = UseLoV2 ? LoV2 : HiV2;
9989       for (int i = 0; i < SplitNumElements; ++i)
9990         if (BlendMask[i] >= SplitNumElements)
9991           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9992     }
9993     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9994   };
9995   SDValue Lo = HalfBlend(LoMask);
9996   SDValue Hi = HalfBlend(HiMask);
9997   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9998 }
9999
10000 /// \brief Either split a vector in halves or decompose the shuffles and the
10001 /// blend.
10002 ///
10003 /// This is provided as a good fallback for many lowerings of non-single-input
10004 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10005 /// between splitting the shuffle into 128-bit components and stitching those
10006 /// back together vs. extracting the single-input shuffles and blending those
10007 /// results.
10008 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10009                                                 SDValue V2, ArrayRef<int> Mask,
10010                                                 SelectionDAG &DAG) {
10011   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10012                                             "lower single-input shuffles as it "
10013                                             "could then recurse on itself.");
10014   int Size = Mask.size();
10015
10016   // If this can be modeled as a broadcast of two elements followed by a blend,
10017   // prefer that lowering. This is especially important because broadcasts can
10018   // often fold with memory operands.
10019   auto DoBothBroadcast = [&] {
10020     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10021     for (int M : Mask)
10022       if (M >= Size) {
10023         if (V2BroadcastIdx == -1)
10024           V2BroadcastIdx = M - Size;
10025         else if (M - Size != V2BroadcastIdx)
10026           return false;
10027       } else if (M >= 0) {
10028         if (V1BroadcastIdx == -1)
10029           V1BroadcastIdx = M;
10030         else if (M != V1BroadcastIdx)
10031           return false;
10032       }
10033     return true;
10034   };
10035   if (DoBothBroadcast())
10036     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10037                                                       DAG);
10038
10039   // If the inputs all stem from a single 128-bit lane of each input, then we
10040   // split them rather than blending because the split will decompose to
10041   // unusually few instructions.
10042   int LaneCount = VT.getSizeInBits() / 128;
10043   int LaneSize = Size / LaneCount;
10044   SmallBitVector LaneInputs[2];
10045   LaneInputs[0].resize(LaneCount, false);
10046   LaneInputs[1].resize(LaneCount, false);
10047   for (int i = 0; i < Size; ++i)
10048     if (Mask[i] >= 0)
10049       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10050   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10051     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10052
10053   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10054   // that the decomposed single-input shuffles don't end up here.
10055   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10056 }
10057
10058 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10059 /// a permutation and blend of those lanes.
10060 ///
10061 /// This essentially blends the out-of-lane inputs to each lane into the lane
10062 /// from a permuted copy of the vector. This lowering strategy results in four
10063 /// instructions in the worst case for a single-input cross lane shuffle which
10064 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10065 /// of. Special cases for each particular shuffle pattern should be handled
10066 /// prior to trying this lowering.
10067 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10068                                                        SDValue V1, SDValue V2,
10069                                                        ArrayRef<int> Mask,
10070                                                        SelectionDAG &DAG) {
10071   // FIXME: This should probably be generalized for 512-bit vectors as well.
10072   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10073   int LaneSize = Mask.size() / 2;
10074
10075   // If there are only inputs from one 128-bit lane, splitting will in fact be
10076   // less expensive. The flags track whether the given lane contains an element
10077   // that crosses to another lane.
10078   bool LaneCrossing[2] = {false, false};
10079   for (int i = 0, Size = Mask.size(); i < Size; ++i)
10080     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10081       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10082   if (!LaneCrossing[0] || !LaneCrossing[1])
10083     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10084
10085   if (isSingleInputShuffleMask(Mask)) {
10086     SmallVector<int, 32> FlippedBlendMask;
10087     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10088       FlippedBlendMask.push_back(
10089           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10090                                   ? Mask[i]
10091                                   : Mask[i] % LaneSize +
10092                                         (i / LaneSize) * LaneSize + Size));
10093
10094     // Flip the vector, and blend the results which should now be in-lane. The
10095     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10096     // 5 for the high source. The value 3 selects the high half of source 2 and
10097     // the value 2 selects the low half of source 2. We only use source 2 to
10098     // allow folding it into a memory operand.
10099     unsigned PERMMask = 3 | 2 << 4;
10100     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10101                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10102     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10103   }
10104
10105   // This now reduces to two single-input shuffles of V1 and V2 which at worst
10106   // will be handled by the above logic and a blend of the results, much like
10107   // other patterns in AVX.
10108   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10109 }
10110
10111 /// \brief Handle lowering 2-lane 128-bit shuffles.
10112 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10113                                         SDValue V2, ArrayRef<int> Mask,
10114                                         const X86Subtarget *Subtarget,
10115                                         SelectionDAG &DAG) {
10116   // TODO: If minimizing size and one of the inputs is a zero vector and the
10117   // the zero vector has only one use, we could use a VPERM2X128 to save the
10118   // instruction bytes needed to explicitly generate the zero vector.
10119
10120   // Blends are faster and handle all the non-lane-crossing cases.
10121   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10122                                                 Subtarget, DAG))
10123     return Blend;
10124
10125   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10126   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10127
10128   // If either input operand is a zero vector, use VPERM2X128 because its mask
10129   // allows us to replace the zero input with an implicit zero.
10130   if (!IsV1Zero && !IsV2Zero) {
10131     // Check for patterns which can be matched with a single insert of a 128-bit
10132     // subvector.
10133     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10134     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10135       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10136                                    VT.getVectorNumElements() / 2);
10137       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10138                                 DAG.getIntPtrConstant(0, DL));
10139       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10140                                 OnlyUsesV1 ? V1 : V2,
10141                                 DAG.getIntPtrConstant(0, DL));
10142       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10143     }
10144   }
10145
10146   // Otherwise form a 128-bit permutation. After accounting for undefs,
10147   // convert the 64-bit shuffle mask selection values into 128-bit
10148   // selection bits by dividing the indexes by 2 and shifting into positions
10149   // defined by a vperm2*128 instruction's immediate control byte.
10150
10151   // The immediate permute control byte looks like this:
10152   //    [1:0] - select 128 bits from sources for low half of destination
10153   //    [2]   - ignore
10154   //    [3]   - zero low half of destination
10155   //    [5:4] - select 128 bits from sources for high half of destination
10156   //    [6]   - ignore
10157   //    [7]   - zero high half of destination
10158
10159   int MaskLO = Mask[0];
10160   if (MaskLO == SM_SentinelUndef)
10161     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10162
10163   int MaskHI = Mask[2];
10164   if (MaskHI == SM_SentinelUndef)
10165     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10166
10167   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10168
10169   // If either input is a zero vector, replace it with an undef input.
10170   // Shuffle mask values <  4 are selecting elements of V1.
10171   // Shuffle mask values >= 4 are selecting elements of V2.
10172   // Adjust each half of the permute mask by clearing the half that was
10173   // selecting the zero vector and setting the zero mask bit.
10174   if (IsV1Zero) {
10175     V1 = DAG.getUNDEF(VT);
10176     if (MaskLO < 4)
10177       PermMask = (PermMask & 0xf0) | 0x08;
10178     if (MaskHI < 4)
10179       PermMask = (PermMask & 0x0f) | 0x80;
10180   }
10181   if (IsV2Zero) {
10182     V2 = DAG.getUNDEF(VT);
10183     if (MaskLO >= 4)
10184       PermMask = (PermMask & 0xf0) | 0x08;
10185     if (MaskHI >= 4)
10186       PermMask = (PermMask & 0x0f) | 0x80;
10187   }
10188
10189   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10190                      DAG.getConstant(PermMask, DL, MVT::i8));
10191 }
10192
10193 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10194 /// shuffling each lane.
10195 ///
10196 /// This will only succeed when the result of fixing the 128-bit lanes results
10197 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10198 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10199 /// the lane crosses early and then use simpler shuffles within each lane.
10200 ///
10201 /// FIXME: It might be worthwhile at some point to support this without
10202 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10203 /// in x86 only floating point has interesting non-repeating shuffles, and even
10204 /// those are still *marginally* more expensive.
10205 static SDValue lowerVectorShuffleByMerging128BitLanes(
10206     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10207     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10208   assert(!isSingleInputShuffleMask(Mask) &&
10209          "This is only useful with multiple inputs.");
10210
10211   int Size = Mask.size();
10212   int LaneSize = 128 / VT.getScalarSizeInBits();
10213   int NumLanes = Size / LaneSize;
10214   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10215
10216   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10217   // check whether the in-128-bit lane shuffles share a repeating pattern.
10218   SmallVector<int, 4> Lanes;
10219   Lanes.resize(NumLanes, -1);
10220   SmallVector<int, 4> InLaneMask;
10221   InLaneMask.resize(LaneSize, -1);
10222   for (int i = 0; i < Size; ++i) {
10223     if (Mask[i] < 0)
10224       continue;
10225
10226     int j = i / LaneSize;
10227
10228     if (Lanes[j] < 0) {
10229       // First entry we've seen for this lane.
10230       Lanes[j] = Mask[i] / LaneSize;
10231     } else if (Lanes[j] != Mask[i] / LaneSize) {
10232       // This doesn't match the lane selected previously!
10233       return SDValue();
10234     }
10235
10236     // Check that within each lane we have a consistent shuffle mask.
10237     int k = i % LaneSize;
10238     if (InLaneMask[k] < 0) {
10239       InLaneMask[k] = Mask[i] % LaneSize;
10240     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10241       // This doesn't fit a repeating in-lane mask.
10242       return SDValue();
10243     }
10244   }
10245
10246   // First shuffle the lanes into place.
10247   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10248                                 VT.getSizeInBits() / 64);
10249   SmallVector<int, 8> LaneMask;
10250   LaneMask.resize(NumLanes * 2, -1);
10251   for (int i = 0; i < NumLanes; ++i)
10252     if (Lanes[i] >= 0) {
10253       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10254       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10255     }
10256
10257   V1 = DAG.getBitcast(LaneVT, V1);
10258   V2 = DAG.getBitcast(LaneVT, V2);
10259   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10260
10261   // Cast it back to the type we actually want.
10262   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10263
10264   // Now do a simple shuffle that isn't lane crossing.
10265   SmallVector<int, 8> NewMask;
10266   NewMask.resize(Size, -1);
10267   for (int i = 0; i < Size; ++i)
10268     if (Mask[i] >= 0)
10269       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10270   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10271          "Must not introduce lane crosses at this point!");
10272
10273   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10274 }
10275
10276 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10277 /// given mask.
10278 ///
10279 /// This returns true if the elements from a particular input are already in the
10280 /// slot required by the given mask and require no permutation.
10281 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10282   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10283   int Size = Mask.size();
10284   for (int i = 0; i < Size; ++i)
10285     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10286       return false;
10287
10288   return true;
10289 }
10290
10291 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10292                                             ArrayRef<int> Mask, SDValue V1,
10293                                             SDValue V2, SelectionDAG &DAG) {
10294
10295   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
10296   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
10297   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10298   int NumElts = VT.getVectorNumElements();
10299   bool ShufpdMask = true;
10300   bool CommutableMask = true;
10301   unsigned Immediate = 0;
10302   for (int i = 0; i < NumElts; ++i) {
10303     if (Mask[i] < 0)
10304       continue;
10305     int Val = (i & 6) + NumElts * (i & 1);
10306     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10307     if (Mask[i] < Val ||  Mask[i] > Val + 1)
10308       ShufpdMask = false;
10309     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
10310       CommutableMask = false;
10311     Immediate |= (Mask[i] % 2) << i;
10312   }
10313   if (ShufpdMask)
10314     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10315                        DAG.getConstant(Immediate, DL, MVT::i8));
10316   if (CommutableMask)
10317     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10318                        DAG.getConstant(Immediate, DL, MVT::i8));
10319   return SDValue();
10320 }
10321
10322 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10323 ///
10324 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10325 /// isn't available.
10326 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10327                                        const X86Subtarget *Subtarget,
10328                                        SelectionDAG &DAG) {
10329   SDLoc DL(Op);
10330   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10331   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10332   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10333   ArrayRef<int> Mask = SVOp->getMask();
10334   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10335
10336   SmallVector<int, 4> WidenedMask;
10337   if (canWidenShuffleElements(Mask, WidenedMask))
10338     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10339                                     DAG);
10340
10341   if (isSingleInputShuffleMask(Mask)) {
10342     // Check for being able to broadcast a single element.
10343     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10344                                                           Mask, Subtarget, DAG))
10345       return Broadcast;
10346
10347     // Use low duplicate instructions for masks that match their pattern.
10348     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10349       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10350
10351     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10352       // Non-half-crossing single input shuffles can be lowerid with an
10353       // interleaved permutation.
10354       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10355                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10356       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10357                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10358     }
10359
10360     // With AVX2 we have direct support for this permutation.
10361     if (Subtarget->hasAVX2())
10362       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10363                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10364
10365     // Otherwise, fall back.
10366     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10367                                                    DAG);
10368   }
10369
10370   // Use dedicated unpack instructions for masks that match their pattern.
10371   if (SDValue V =
10372           lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10373     return V;
10374
10375   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10376                                                 Subtarget, DAG))
10377     return Blend;
10378
10379   // Check if the blend happens to exactly fit that of SHUFPD.
10380   if (SDValue Op =
10381       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10382     return Op;
10383
10384   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10385   // shuffle. However, if we have AVX2 and either inputs are already in place,
10386   // we will be able to shuffle even across lanes the other input in a single
10387   // instruction so skip this pattern.
10388   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10389                                  isShuffleMaskInputInPlace(1, Mask))))
10390     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10391             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10392       return Result;
10393
10394   // If we have AVX2 then we always want to lower with a blend because an v4 we
10395   // can fully permute the elements.
10396   if (Subtarget->hasAVX2())
10397     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10398                                                       Mask, DAG);
10399
10400   // Otherwise fall back on generic lowering.
10401   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10402 }
10403
10404 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10405 ///
10406 /// This routine is only called when we have AVX2 and thus a reasonable
10407 /// instruction set for v4i64 shuffling..
10408 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10409                                        const X86Subtarget *Subtarget,
10410                                        SelectionDAG &DAG) {
10411   SDLoc DL(Op);
10412   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10413   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10414   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10415   ArrayRef<int> Mask = SVOp->getMask();
10416   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10417   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10418
10419   SmallVector<int, 4> WidenedMask;
10420   if (canWidenShuffleElements(Mask, WidenedMask))
10421     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10422                                     DAG);
10423
10424   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10425                                                 Subtarget, DAG))
10426     return Blend;
10427
10428   // Check for being able to broadcast a single element.
10429   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10430                                                         Mask, Subtarget, DAG))
10431     return Broadcast;
10432
10433   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10434   // use lower latency instructions that will operate on both 128-bit lanes.
10435   SmallVector<int, 2> RepeatedMask;
10436   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10437     if (isSingleInputShuffleMask(Mask)) {
10438       int PSHUFDMask[] = {-1, -1, -1, -1};
10439       for (int i = 0; i < 2; ++i)
10440         if (RepeatedMask[i] >= 0) {
10441           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10442           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10443         }
10444       return DAG.getBitcast(
10445           MVT::v4i64,
10446           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10447                       DAG.getBitcast(MVT::v8i32, V1),
10448                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10449     }
10450   }
10451
10452   // AVX2 provides a direct instruction for permuting a single input across
10453   // lanes.
10454   if (isSingleInputShuffleMask(Mask))
10455     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10456                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10457
10458   // Try to use shift instructions.
10459   if (SDValue Shift =
10460           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10461     return Shift;
10462
10463   // Use dedicated unpack instructions for masks that match their pattern.
10464   if (SDValue V =
10465           lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10466     return V;
10467
10468   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10469   // shuffle. However, if we have AVX2 and either inputs are already in place,
10470   // we will be able to shuffle even across lanes the other input in a single
10471   // instruction so skip this pattern.
10472   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10473                                  isShuffleMaskInputInPlace(1, Mask))))
10474     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10475             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10476       return Result;
10477
10478   // Otherwise fall back on generic blend lowering.
10479   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10480                                                     Mask, DAG);
10481 }
10482
10483 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10484 ///
10485 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10486 /// isn't available.
10487 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10488                                        const X86Subtarget *Subtarget,
10489                                        SelectionDAG &DAG) {
10490   SDLoc DL(Op);
10491   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10492   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10493   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10494   ArrayRef<int> Mask = SVOp->getMask();
10495   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10496
10497   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10498                                                 Subtarget, DAG))
10499     return Blend;
10500
10501   // Check for being able to broadcast a single element.
10502   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10503                                                         Mask, Subtarget, DAG))
10504     return Broadcast;
10505
10506   // If the shuffle mask is repeated in each 128-bit lane, we have many more
10507   // options to efficiently lower the shuffle.
10508   SmallVector<int, 4> RepeatedMask;
10509   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10510     assert(RepeatedMask.size() == 4 &&
10511            "Repeated masks must be half the mask width!");
10512
10513     // Use even/odd duplicate instructions for masks that match their pattern.
10514     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10515       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10516     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10517       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10518
10519     if (isSingleInputShuffleMask(Mask))
10520       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10521                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10522
10523     // Use dedicated unpack instructions for masks that match their pattern.
10524     if (SDValue V =
10525             lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10526       return V;
10527
10528     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10529     // have already handled any direct blends. We also need to squash the
10530     // repeated mask into a simulated v4f32 mask.
10531     for (int i = 0; i < 4; ++i)
10532       if (RepeatedMask[i] >= 8)
10533         RepeatedMask[i] -= 4;
10534     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10535   }
10536
10537   // If we have a single input shuffle with different shuffle patterns in the
10538   // two 128-bit lanes use the variable mask to VPERMILPS.
10539   if (isSingleInputShuffleMask(Mask)) {
10540     SDValue VPermMask[8];
10541     for (int i = 0; i < 8; ++i)
10542       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10543                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10544     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10545       return DAG.getNode(
10546           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10547           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10548
10549     if (Subtarget->hasAVX2())
10550       return DAG.getNode(
10551           X86ISD::VPERMV, DL, MVT::v8f32,
10552           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10553                                                  MVT::v8i32, VPermMask)),
10554           V1);
10555
10556     // Otherwise, fall back.
10557     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10558                                                    DAG);
10559   }
10560
10561   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10562   // shuffle.
10563   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10564           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10565     return Result;
10566
10567   // If we have AVX2 then we always want to lower with a blend because at v8 we
10568   // can fully permute the elements.
10569   if (Subtarget->hasAVX2())
10570     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10571                                                       Mask, DAG);
10572
10573   // Otherwise fall back on generic lowering.
10574   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10575 }
10576
10577 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10578 ///
10579 /// This routine is only called when we have AVX2 and thus a reasonable
10580 /// instruction set for v8i32 shuffling..
10581 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10582                                        const X86Subtarget *Subtarget,
10583                                        SelectionDAG &DAG) {
10584   SDLoc DL(Op);
10585   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10586   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10587   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10588   ArrayRef<int> Mask = SVOp->getMask();
10589   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10590   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10591
10592   // Whenever we can lower this as a zext, that instruction is strictly faster
10593   // than any alternative. It also allows us to fold memory operands into the
10594   // shuffle in many cases.
10595   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10596                                                          Mask, Subtarget, DAG))
10597     return ZExt;
10598
10599   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10600                                                 Subtarget, DAG))
10601     return Blend;
10602
10603   // Check for being able to broadcast a single element.
10604   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10605                                                         Mask, Subtarget, DAG))
10606     return Broadcast;
10607
10608   // If the shuffle mask is repeated in each 128-bit lane we can use more
10609   // efficient instructions that mirror the shuffles across the two 128-bit
10610   // lanes.
10611   SmallVector<int, 4> RepeatedMask;
10612   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10613     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10614     if (isSingleInputShuffleMask(Mask))
10615       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10616                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10617
10618     // Use dedicated unpack instructions for masks that match their pattern.
10619     if (SDValue V =
10620             lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10621       return V;
10622   }
10623
10624   // Try to use shift instructions.
10625   if (SDValue Shift =
10626           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10627     return Shift;
10628
10629   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10630           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10631     return Rotate;
10632
10633   // If the shuffle patterns aren't repeated but it is a single input, directly
10634   // generate a cross-lane VPERMD instruction.
10635   if (isSingleInputShuffleMask(Mask)) {
10636     SDValue VPermMask[8];
10637     for (int i = 0; i < 8; ++i)
10638       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10639                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10640     return DAG.getNode(
10641         X86ISD::VPERMV, DL, MVT::v8i32,
10642         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10643   }
10644
10645   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10646   // shuffle.
10647   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10648           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10649     return Result;
10650
10651   // Otherwise fall back on generic blend lowering.
10652   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10653                                                     Mask, DAG);
10654 }
10655
10656 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10657 ///
10658 /// This routine is only called when we have AVX2 and thus a reasonable
10659 /// instruction set for v16i16 shuffling..
10660 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10661                                         const X86Subtarget *Subtarget,
10662                                         SelectionDAG &DAG) {
10663   SDLoc DL(Op);
10664   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10665   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10667   ArrayRef<int> Mask = SVOp->getMask();
10668   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10669   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10670
10671   // Whenever we can lower this as a zext, that instruction is strictly faster
10672   // than any alternative. It also allows us to fold memory operands into the
10673   // shuffle in many cases.
10674   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10675                                                          Mask, Subtarget, DAG))
10676     return ZExt;
10677
10678   // Check for being able to broadcast a single element.
10679   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10680                                                         Mask, Subtarget, DAG))
10681     return Broadcast;
10682
10683   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10684                                                 Subtarget, DAG))
10685     return Blend;
10686
10687   // Use dedicated unpack instructions for masks that match their pattern.
10688   if (SDValue V =
10689           lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10690     return V;
10691
10692   // Try to use shift instructions.
10693   if (SDValue Shift =
10694           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10695     return Shift;
10696
10697   // Try to use byte rotation instructions.
10698   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10699           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10700     return Rotate;
10701
10702   if (isSingleInputShuffleMask(Mask)) {
10703     // There are no generalized cross-lane shuffle operations available on i16
10704     // element types.
10705     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10706       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10707                                                      Mask, DAG);
10708
10709     SmallVector<int, 8> RepeatedMask;
10710     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10711       // As this is a single-input shuffle, the repeated mask should be
10712       // a strictly valid v8i16 mask that we can pass through to the v8i16
10713       // lowering to handle even the v16 case.
10714       return lowerV8I16GeneralSingleInputVectorShuffle(
10715           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10716     }
10717
10718     SDValue PSHUFBMask[32];
10719     for (int i = 0; i < 16; ++i) {
10720       if (Mask[i] == -1) {
10721         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10722         continue;
10723       }
10724
10725       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10726       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10727       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10728       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10729     }
10730     return DAG.getBitcast(MVT::v16i16,
10731                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10732                                       DAG.getBitcast(MVT::v32i8, V1),
10733                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10734                                                   MVT::v32i8, PSHUFBMask)));
10735   }
10736
10737   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10738   // shuffle.
10739   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10740           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10741     return Result;
10742
10743   // Otherwise fall back on generic lowering.
10744   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10745 }
10746
10747 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10748 ///
10749 /// This routine is only called when we have AVX2 and thus a reasonable
10750 /// instruction set for v32i8 shuffling..
10751 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10752                                        const X86Subtarget *Subtarget,
10753                                        SelectionDAG &DAG) {
10754   SDLoc DL(Op);
10755   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10756   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10757   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10758   ArrayRef<int> Mask = SVOp->getMask();
10759   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10760   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10761
10762   // Whenever we can lower this as a zext, that instruction is strictly faster
10763   // than any alternative. It also allows us to fold memory operands into the
10764   // shuffle in many cases.
10765   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10766                                                          Mask, Subtarget, DAG))
10767     return ZExt;
10768
10769   // Check for being able to broadcast a single element.
10770   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10771                                                         Mask, Subtarget, DAG))
10772     return Broadcast;
10773
10774   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10775                                                 Subtarget, DAG))
10776     return Blend;
10777
10778   // Use dedicated unpack instructions for masks that match their pattern.
10779   if (SDValue V =
10780           lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10781     return V;
10782
10783   // Try to use shift instructions.
10784   if (SDValue Shift =
10785           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10786     return Shift;
10787
10788   // Try to use byte rotation instructions.
10789   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10790           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10791     return Rotate;
10792
10793   if (isSingleInputShuffleMask(Mask)) {
10794     // There are no generalized cross-lane shuffle operations available on i8
10795     // element types.
10796     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10797       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10798                                                      Mask, DAG);
10799
10800     SDValue PSHUFBMask[32];
10801     for (int i = 0; i < 32; ++i)
10802       PSHUFBMask[i] =
10803           Mask[i] < 0
10804               ? DAG.getUNDEF(MVT::i8)
10805               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10806                                 MVT::i8);
10807
10808     return DAG.getNode(
10809         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10810         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10811   }
10812
10813   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10814   // shuffle.
10815   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10816           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10817     return Result;
10818
10819   // Otherwise fall back on generic lowering.
10820   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10821 }
10822
10823 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10824 ///
10825 /// This routine either breaks down the specific type of a 256-bit x86 vector
10826 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10827 /// together based on the available instructions.
10828 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10829                                         MVT VT, const X86Subtarget *Subtarget,
10830                                         SelectionDAG &DAG) {
10831   SDLoc DL(Op);
10832   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10833   ArrayRef<int> Mask = SVOp->getMask();
10834
10835   // If we have a single input to the zero element, insert that into V1 if we
10836   // can do so cheaply.
10837   int NumElts = VT.getVectorNumElements();
10838   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10839     return M >= NumElts;
10840   });
10841
10842   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10843     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10844                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10845       return Insertion;
10846
10847   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10848   // can check for those subtargets here and avoid much of the subtarget
10849   // querying in the per-vector-type lowering routines. With AVX1 we have
10850   // essentially *zero* ability to manipulate a 256-bit vector with integer
10851   // types. Since we'll use floating point types there eventually, just
10852   // immediately cast everything to a float and operate entirely in that domain.
10853   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10854     int ElementBits = VT.getScalarSizeInBits();
10855     if (ElementBits < 32)
10856       // No floating point type available, decompose into 128-bit vectors.
10857       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10858
10859     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10860                                 VT.getVectorNumElements());
10861     V1 = DAG.getBitcast(FpVT, V1);
10862     V2 = DAG.getBitcast(FpVT, V2);
10863     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10864   }
10865
10866   switch (VT.SimpleTy) {
10867   case MVT::v4f64:
10868     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10869   case MVT::v4i64:
10870     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10871   case MVT::v8f32:
10872     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10873   case MVT::v8i32:
10874     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10875   case MVT::v16i16:
10876     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10877   case MVT::v32i8:
10878     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10879
10880   default:
10881     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10882   }
10883 }
10884
10885 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10886 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10887                                         ArrayRef<int> Mask,
10888                                         SDValue V1, SDValue V2,
10889                                         SelectionDAG &DAG) {
10890   assert(VT.getScalarSizeInBits() == 64 &&
10891          "Unexpected element type size for 128bit shuffle.");
10892
10893   // To handle 256 bit vector requires VLX and most probably
10894   // function lowerV2X128VectorShuffle() is better solution.
10895   assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
10896
10897   SmallVector<int, 4> WidenedMask;
10898   if (!canWidenShuffleElements(Mask, WidenedMask))
10899     return SDValue();
10900
10901   // Form a 128-bit permutation.
10902   // Convert the 64-bit shuffle mask selection values into 128-bit selection
10903   // bits defined by a vshuf64x2 instruction's immediate control byte.
10904   unsigned PermMask = 0, Imm = 0;
10905   unsigned ControlBitsNum = WidenedMask.size() / 2;
10906
10907   for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10908     if (WidenedMask[i] == SM_SentinelZero)
10909       return SDValue();
10910
10911     // Use first element in place of undef mask.
10912     Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10913     PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10914   }
10915
10916   return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10917                      DAG.getConstant(PermMask, DL, MVT::i8));
10918 }
10919
10920 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10921                                            ArrayRef<int> Mask, SDValue V1,
10922                                            SDValue V2, SelectionDAG &DAG) {
10923
10924   assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10925
10926   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10927   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10928
10929   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10930   if (isSingleInputShuffleMask(Mask))
10931     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10932
10933   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10934 }
10935
10936 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10937 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10938                                        const X86Subtarget *Subtarget,
10939                                        SelectionDAG &DAG) {
10940   SDLoc DL(Op);
10941   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10942   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10943   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10944   ArrayRef<int> Mask = SVOp->getMask();
10945   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10946
10947   if (SDValue Shuf128 =
10948           lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10949     return Shuf128;
10950
10951   if (SDValue Unpck =
10952           lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10953     return Unpck;
10954
10955   return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10956 }
10957
10958 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10959 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10960                                         const X86Subtarget *Subtarget,
10961                                         SelectionDAG &DAG) {
10962   SDLoc DL(Op);
10963   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10964   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10965   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10966   ArrayRef<int> Mask = SVOp->getMask();
10967   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10968
10969   if (SDValue Unpck =
10970           lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10971     return Unpck;
10972
10973   return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10974 }
10975
10976 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10977 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10978                                        const X86Subtarget *Subtarget,
10979                                        SelectionDAG &DAG) {
10980   SDLoc DL(Op);
10981   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10982   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10983   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10984   ArrayRef<int> Mask = SVOp->getMask();
10985   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10986
10987   if (SDValue Shuf128 =
10988           lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
10989     return Shuf128;
10990
10991   if (SDValue Unpck =
10992           lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10993     return Unpck;
10994
10995   return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10996 }
10997
10998 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10999 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11000                                         const X86Subtarget *Subtarget,
11001                                         SelectionDAG &DAG) {
11002   SDLoc DL(Op);
11003   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11004   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11005   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11006   ArrayRef<int> Mask = SVOp->getMask();
11007   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11008
11009   if (SDValue Unpck =
11010           lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11011     return Unpck;
11012
11013   return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11014 }
11015
11016 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11017 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11018                                         const X86Subtarget *Subtarget,
11019                                         SelectionDAG &DAG) {
11020   SDLoc DL(Op);
11021   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11022   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11023   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11024   ArrayRef<int> Mask = SVOp->getMask();
11025   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11026   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11027
11028   return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11029 }
11030
11031 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11032 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11033                                        const X86Subtarget *Subtarget,
11034                                        SelectionDAG &DAG) {
11035   SDLoc DL(Op);
11036   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11037   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11038   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11039   ArrayRef<int> Mask = SVOp->getMask();
11040   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11041   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11042
11043   // FIXME: Implement direct support for this type!
11044   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11045 }
11046
11047 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11048 ///
11049 /// This routine either breaks down the specific type of a 512-bit x86 vector
11050 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11051 /// together based on the available instructions.
11052 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11053                                         MVT VT, const X86Subtarget *Subtarget,
11054                                         SelectionDAG &DAG) {
11055   SDLoc DL(Op);
11056   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11057   ArrayRef<int> Mask = SVOp->getMask();
11058   assert(Subtarget->hasAVX512() &&
11059          "Cannot lower 512-bit vectors w/ basic ISA!");
11060
11061   // Check for being able to broadcast a single element.
11062   if (SDValue Broadcast =
11063           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11064     return Broadcast;
11065
11066   // Dispatch to each element type for lowering. If we don't have supprot for
11067   // specific element type shuffles at 512 bits, immediately split them and
11068   // lower them. Each lowering routine of a given type is allowed to assume that
11069   // the requisite ISA extensions for that element type are available.
11070   switch (VT.SimpleTy) {
11071   case MVT::v8f64:
11072     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11073   case MVT::v16f32:
11074     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11075   case MVT::v8i64:
11076     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11077   case MVT::v16i32:
11078     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11079   case MVT::v32i16:
11080     if (Subtarget->hasBWI())
11081       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11082     break;
11083   case MVT::v64i8:
11084     if (Subtarget->hasBWI())
11085       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11086     break;
11087
11088   default:
11089     llvm_unreachable("Not a valid 512-bit x86 vector type!");
11090   }
11091
11092   // Otherwise fall back on splitting.
11093   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11094 }
11095
11096 // Lower vXi1 vector shuffles.
11097 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11098 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11099 // vector, shuffle and then truncate it back.
11100 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11101                                       MVT VT, const X86Subtarget *Subtarget,
11102                                       SelectionDAG &DAG) {
11103   SDLoc DL(Op);
11104   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11105   ArrayRef<int> Mask = SVOp->getMask();
11106   assert(Subtarget->hasAVX512() &&
11107          "Cannot lower 512-bit vectors w/o basic ISA!");
11108   MVT ExtVT;
11109   switch (VT.SimpleTy) {
11110   default:
11111     llvm_unreachable("Expected a vector of i1 elements");
11112   case MVT::v2i1:
11113     ExtVT = MVT::v2i64;
11114     break;
11115   case MVT::v4i1:
11116     ExtVT = MVT::v4i32;
11117     break;
11118   case MVT::v8i1:
11119     ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11120     break;
11121   case MVT::v16i1:
11122     ExtVT = MVT::v16i32;
11123     break;
11124   case MVT::v32i1:
11125     ExtVT = MVT::v32i16;
11126     break;
11127   case MVT::v64i1:
11128     ExtVT = MVT::v64i8;
11129     break;
11130   }
11131
11132   if (ISD::isBuildVectorAllZeros(V1.getNode()))
11133     V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11134   else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11135     V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11136   else
11137     V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11138
11139   if (V2.isUndef())
11140     V2 = DAG.getUNDEF(ExtVT);
11141   else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11142     V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11143   else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11144     V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11145   else
11146     V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11147   return DAG.getNode(ISD::TRUNCATE, DL, VT,
11148                      DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11149 }
11150 /// \brief Top-level lowering for x86 vector shuffles.
11151 ///
11152 /// This handles decomposition, canonicalization, and lowering of all x86
11153 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11154 /// above in helper routines. The canonicalization attempts to widen shuffles
11155 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11156 /// s.t. only one of the two inputs needs to be tested, etc.
11157 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11158                                   SelectionDAG &DAG) {
11159   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11160   ArrayRef<int> Mask = SVOp->getMask();
11161   SDValue V1 = Op.getOperand(0);
11162   SDValue V2 = Op.getOperand(1);
11163   MVT VT = Op.getSimpleValueType();
11164   int NumElements = VT.getVectorNumElements();
11165   SDLoc dl(Op);
11166   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11167
11168   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11169          "Can't lower MMX shuffles");
11170
11171   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11172   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11173   if (V1IsUndef && V2IsUndef)
11174     return DAG.getUNDEF(VT);
11175
11176   // When we create a shuffle node we put the UNDEF node to second operand,
11177   // but in some cases the first operand may be transformed to UNDEF.
11178   // In this case we should just commute the node.
11179   if (V1IsUndef)
11180     return DAG.getCommutedVectorShuffle(*SVOp);
11181
11182   // Check for non-undef masks pointing at an undef vector and make the masks
11183   // undef as well. This makes it easier to match the shuffle based solely on
11184   // the mask.
11185   if (V2IsUndef)
11186     for (int M : Mask)
11187       if (M >= NumElements) {
11188         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11189         for (int &M : NewMask)
11190           if (M >= NumElements)
11191             M = -1;
11192         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11193       }
11194
11195   // We actually see shuffles that are entirely re-arrangements of a set of
11196   // zero inputs. This mostly happens while decomposing complex shuffles into
11197   // simple ones. Directly lower these as a buildvector of zeros.
11198   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11199   if (Zeroable.all())
11200     return getZeroVector(VT, Subtarget, DAG, dl);
11201
11202   // Try to collapse shuffles into using a vector type with fewer elements but
11203   // wider element types. We cap this to not form integers or floating point
11204   // elements wider than 64 bits, but it might be interesting to form i128
11205   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11206   SmallVector<int, 16> WidenedMask;
11207   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11208       canWidenShuffleElements(Mask, WidenedMask)) {
11209     MVT NewEltVT = VT.isFloatingPoint()
11210                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11211                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11212     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11213     // Make sure that the new vector type is legal. For example, v2f64 isn't
11214     // legal on SSE1.
11215     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11216       V1 = DAG.getBitcast(NewVT, V1);
11217       V2 = DAG.getBitcast(NewVT, V2);
11218       return DAG.getBitcast(
11219           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11220     }
11221   }
11222
11223   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11224   for (int M : SVOp->getMask())
11225     if (M < 0)
11226       ++NumUndefElements;
11227     else if (M < NumElements)
11228       ++NumV1Elements;
11229     else
11230       ++NumV2Elements;
11231
11232   // Commute the shuffle as needed such that more elements come from V1 than
11233   // V2. This allows us to match the shuffle pattern strictly on how many
11234   // elements come from V1 without handling the symmetric cases.
11235   if (NumV2Elements > NumV1Elements)
11236     return DAG.getCommutedVectorShuffle(*SVOp);
11237
11238   // When the number of V1 and V2 elements are the same, try to minimize the
11239   // number of uses of V2 in the low half of the vector. When that is tied,
11240   // ensure that the sum of indices for V1 is equal to or lower than the sum
11241   // indices for V2. When those are equal, try to ensure that the number of odd
11242   // indices for V1 is lower than the number of odd indices for V2.
11243   if (NumV1Elements == NumV2Elements) {
11244     int LowV1Elements = 0, LowV2Elements = 0;
11245     for (int M : SVOp->getMask().slice(0, NumElements / 2))
11246       if (M >= NumElements)
11247         ++LowV2Elements;
11248       else if (M >= 0)
11249         ++LowV1Elements;
11250     if (LowV2Elements > LowV1Elements) {
11251       return DAG.getCommutedVectorShuffle(*SVOp);
11252     } else if (LowV2Elements == LowV1Elements) {
11253       int SumV1Indices = 0, SumV2Indices = 0;
11254       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11255         if (SVOp->getMask()[i] >= NumElements)
11256           SumV2Indices += i;
11257         else if (SVOp->getMask()[i] >= 0)
11258           SumV1Indices += i;
11259       if (SumV2Indices < SumV1Indices) {
11260         return DAG.getCommutedVectorShuffle(*SVOp);
11261       } else if (SumV2Indices == SumV1Indices) {
11262         int NumV1OddIndices = 0, NumV2OddIndices = 0;
11263         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11264           if (SVOp->getMask()[i] >= NumElements)
11265             NumV2OddIndices += i % 2;
11266           else if (SVOp->getMask()[i] >= 0)
11267             NumV1OddIndices += i % 2;
11268         if (NumV2OddIndices < NumV1OddIndices)
11269           return DAG.getCommutedVectorShuffle(*SVOp);
11270       }
11271     }
11272   }
11273
11274   // For each vector width, delegate to a specialized lowering routine.
11275   if (VT.is128BitVector())
11276     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11277
11278   if (VT.is256BitVector())
11279     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11280
11281   if (VT.is512BitVector())
11282     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11283
11284   if (Is1BitVector)
11285     return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11286   llvm_unreachable("Unimplemented!");
11287 }
11288
11289 // This function assumes its argument is a BUILD_VECTOR of constants or
11290 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11291 // true.
11292 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11293                                     unsigned &MaskValue) {
11294   MaskValue = 0;
11295   unsigned NumElems = BuildVector->getNumOperands();
11296
11297   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11298   // We don't handle the >2 lanes case right now.
11299   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11300   if (NumLanes > 2)
11301     return false;
11302
11303   unsigned NumElemsInLane = NumElems / NumLanes;
11304
11305   // Blend for v16i16 should be symmetric for the both lanes.
11306   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11307     SDValue EltCond = BuildVector->getOperand(i);
11308     SDValue SndLaneEltCond =
11309         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11310
11311     int Lane1Cond = -1, Lane2Cond = -1;
11312     if (isa<ConstantSDNode>(EltCond))
11313       Lane1Cond = !isZero(EltCond);
11314     if (isa<ConstantSDNode>(SndLaneEltCond))
11315       Lane2Cond = !isZero(SndLaneEltCond);
11316
11317     unsigned LaneMask = 0;
11318     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11319       // Lane1Cond != 0, means we want the first argument.
11320       // Lane1Cond == 0, means we want the second argument.
11321       // The encoding of this argument is 0 for the first argument, 1
11322       // for the second. Therefore, invert the condition.
11323       LaneMask = !Lane1Cond << i;
11324     else if (Lane1Cond < 0)
11325       LaneMask = !Lane2Cond << i;
11326     else
11327       return false;
11328
11329     MaskValue |= LaneMask;
11330     if (NumLanes == 2)
11331       MaskValue |= LaneMask << NumElemsInLane;
11332   }
11333   return true;
11334 }
11335
11336 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11337 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11338                                            const X86Subtarget *Subtarget,
11339                                            SelectionDAG &DAG) {
11340   SDValue Cond = Op.getOperand(0);
11341   SDValue LHS = Op.getOperand(1);
11342   SDValue RHS = Op.getOperand(2);
11343   SDLoc dl(Op);
11344   MVT VT = Op.getSimpleValueType();
11345
11346   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11347     return SDValue();
11348   auto *CondBV = cast<BuildVectorSDNode>(Cond);
11349
11350   // Only non-legal VSELECTs reach this lowering, convert those into generic
11351   // shuffles and re-use the shuffle lowering path for blends.
11352   SmallVector<int, 32> Mask;
11353   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11354     SDValue CondElt = CondBV->getOperand(i);
11355     Mask.push_back(
11356         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11357   }
11358   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11359 }
11360
11361 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11362   // A vselect where all conditions and data are constants can be optimized into
11363   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11364   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11365       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11366       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11367     return SDValue();
11368
11369   // Try to lower this to a blend-style vector shuffle. This can handle all
11370   // constant condition cases.
11371   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11372     return BlendOp;
11373
11374   // Variable blends are only legal from SSE4.1 onward.
11375   if (!Subtarget->hasSSE41())
11376     return SDValue();
11377
11378   // Only some types will be legal on some subtargets. If we can emit a legal
11379   // VSELECT-matching blend, return Op, and but if we need to expand, return
11380   // a null value.
11381   switch (Op.getSimpleValueType().SimpleTy) {
11382   default:
11383     // Most of the vector types have blends past SSE4.1.
11384     return Op;
11385
11386   case MVT::v32i8:
11387     // The byte blends for AVX vectors were introduced only in AVX2.
11388     if (Subtarget->hasAVX2())
11389       return Op;
11390
11391     return SDValue();
11392
11393   case MVT::v8i16:
11394   case MVT::v16i16:
11395     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11396     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11397       return Op;
11398
11399     // FIXME: We should custom lower this by fixing the condition and using i8
11400     // blends.
11401     return SDValue();
11402   }
11403 }
11404
11405 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11406   MVT VT = Op.getSimpleValueType();
11407   SDLoc dl(Op);
11408
11409   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11410     return SDValue();
11411
11412   if (VT.getSizeInBits() == 8) {
11413     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11414                                   Op.getOperand(0), Op.getOperand(1));
11415     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11416                                   DAG.getValueType(VT));
11417     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11418   }
11419
11420   if (VT.getSizeInBits() == 16) {
11421     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11422     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11423     if (Idx == 0)
11424       return DAG.getNode(
11425           ISD::TRUNCATE, dl, MVT::i16,
11426           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11427                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11428                       Op.getOperand(1)));
11429     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11430                                   Op.getOperand(0), Op.getOperand(1));
11431     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11432                                   DAG.getValueType(VT));
11433     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11434   }
11435
11436   if (VT == MVT::f32) {
11437     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11438     // the result back to FR32 register. It's only worth matching if the
11439     // result has a single use which is a store or a bitcast to i32.  And in
11440     // the case of a store, it's not worth it if the index is a constant 0,
11441     // because a MOVSSmr can be used instead, which is smaller and faster.
11442     if (!Op.hasOneUse())
11443       return SDValue();
11444     SDNode *User = *Op.getNode()->use_begin();
11445     if ((User->getOpcode() != ISD::STORE ||
11446          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11447           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11448         (User->getOpcode() != ISD::BITCAST ||
11449          User->getValueType(0) != MVT::i32))
11450       return SDValue();
11451     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11452                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11453                                   Op.getOperand(1));
11454     return DAG.getBitcast(MVT::f32, Extract);
11455   }
11456
11457   if (VT == MVT::i32 || VT == MVT::i64) {
11458     // ExtractPS/pextrq works with constant index.
11459     if (isa<ConstantSDNode>(Op.getOperand(1)))
11460       return Op;
11461   }
11462   return SDValue();
11463 }
11464
11465 /// Extract one bit from mask vector, like v16i1 or v8i1.
11466 /// AVX-512 feature.
11467 SDValue
11468 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11469   SDValue Vec = Op.getOperand(0);
11470   SDLoc dl(Vec);
11471   MVT VecVT = Vec.getSimpleValueType();
11472   SDValue Idx = Op.getOperand(1);
11473   MVT EltVT = Op.getSimpleValueType();
11474
11475   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11476   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11477          "Unexpected vector type in ExtractBitFromMaskVector");
11478
11479   // variable index can't be handled in mask registers,
11480   // extend vector to VR512
11481   if (!isa<ConstantSDNode>(Idx)) {
11482     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11483     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11484     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11485                               ExtVT.getVectorElementType(), Ext, Idx);
11486     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11487   }
11488
11489   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11490   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11491   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11492     rc = getRegClassFor(MVT::v16i1);
11493   unsigned MaxSift = rc->getSize()*8 - 1;
11494   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11495                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11496   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11497                     DAG.getConstant(MaxSift, dl, MVT::i8));
11498   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11499                        DAG.getIntPtrConstant(0, dl));
11500 }
11501
11502 SDValue
11503 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11504                                            SelectionDAG &DAG) const {
11505   SDLoc dl(Op);
11506   SDValue Vec = Op.getOperand(0);
11507   MVT VecVT = Vec.getSimpleValueType();
11508   SDValue Idx = Op.getOperand(1);
11509
11510   if (Op.getSimpleValueType() == MVT::i1)
11511     return ExtractBitFromMaskVector(Op, DAG);
11512
11513   if (!isa<ConstantSDNode>(Idx)) {
11514     if (VecVT.is512BitVector() ||
11515         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11516          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11517
11518       MVT MaskEltVT =
11519         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11520       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11521                                     MaskEltVT.getSizeInBits());
11522
11523       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11524       auto PtrVT = getPointerTy(DAG.getDataLayout());
11525       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11526                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11527                                  DAG.getConstant(0, dl, PtrVT));
11528       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11529       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11530                          DAG.getConstant(0, dl, PtrVT));
11531     }
11532     return SDValue();
11533   }
11534
11535   // If this is a 256-bit vector result, first extract the 128-bit vector and
11536   // then extract the element from the 128-bit vector.
11537   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11538
11539     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11540     // Get the 128-bit vector.
11541     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11542     MVT EltVT = VecVT.getVectorElementType();
11543
11544     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11545     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11546
11547     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11548     // this can be done with a mask.
11549     IdxVal &= ElemsPerChunk - 1;
11550     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11551                        DAG.getConstant(IdxVal, dl, MVT::i32));
11552   }
11553
11554   assert(VecVT.is128BitVector() && "Unexpected vector length");
11555
11556   if (Subtarget->hasSSE41())
11557     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11558       return Res;
11559
11560   MVT VT = Op.getSimpleValueType();
11561   // TODO: handle v16i8.
11562   if (VT.getSizeInBits() == 16) {
11563     SDValue Vec = Op.getOperand(0);
11564     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11565     if (Idx == 0)
11566       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11567                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11568                                      DAG.getBitcast(MVT::v4i32, Vec),
11569                                      Op.getOperand(1)));
11570     // Transform it so it match pextrw which produces a 32-bit result.
11571     MVT EltVT = MVT::i32;
11572     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11573                                   Op.getOperand(0), Op.getOperand(1));
11574     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11575                                   DAG.getValueType(VT));
11576     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11577   }
11578
11579   if (VT.getSizeInBits() == 32) {
11580     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11581     if (Idx == 0)
11582       return Op;
11583
11584     // SHUFPS the element to the lowest double word, then movss.
11585     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11586     MVT VVT = Op.getOperand(0).getSimpleValueType();
11587     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11588                                        DAG.getUNDEF(VVT), Mask);
11589     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11590                        DAG.getIntPtrConstant(0, dl));
11591   }
11592
11593   if (VT.getSizeInBits() == 64) {
11594     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11595     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11596     //        to match extract_elt for f64.
11597     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11598     if (Idx == 0)
11599       return Op;
11600
11601     // UNPCKHPD the element to the lowest double word, then movsd.
11602     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11603     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11604     int Mask[2] = { 1, -1 };
11605     MVT VVT = Op.getOperand(0).getSimpleValueType();
11606     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11607                                        DAG.getUNDEF(VVT), Mask);
11608     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11609                        DAG.getIntPtrConstant(0, dl));
11610   }
11611
11612   return SDValue();
11613 }
11614
11615 /// Insert one bit to mask vector, like v16i1 or v8i1.
11616 /// AVX-512 feature.
11617 SDValue
11618 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11619   SDLoc dl(Op);
11620   SDValue Vec = Op.getOperand(0);
11621   SDValue Elt = Op.getOperand(1);
11622   SDValue Idx = Op.getOperand(2);
11623   MVT VecVT = Vec.getSimpleValueType();
11624
11625   if (!isa<ConstantSDNode>(Idx)) {
11626     // Non constant index. Extend source and destination,
11627     // insert element and then truncate the result.
11628     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11629     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11630     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11631       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11632       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11633     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11634   }
11635
11636   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11637   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11638   if (IdxVal)
11639     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11640                            DAG.getConstant(IdxVal, dl, MVT::i8));
11641   if (Vec.getOpcode() == ISD::UNDEF)
11642     return EltInVec;
11643   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11644 }
11645
11646 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11647                                                   SelectionDAG &DAG) const {
11648   MVT VT = Op.getSimpleValueType();
11649   MVT EltVT = VT.getVectorElementType();
11650
11651   if (EltVT == MVT::i1)
11652     return InsertBitToMaskVector(Op, DAG);
11653
11654   SDLoc dl(Op);
11655   SDValue N0 = Op.getOperand(0);
11656   SDValue N1 = Op.getOperand(1);
11657   SDValue N2 = Op.getOperand(2);
11658   if (!isa<ConstantSDNode>(N2))
11659     return SDValue();
11660   auto *N2C = cast<ConstantSDNode>(N2);
11661   unsigned IdxVal = N2C->getZExtValue();
11662
11663   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11664   // into that, and then insert the subvector back into the result.
11665   if (VT.is256BitVector() || VT.is512BitVector()) {
11666     // With a 256-bit vector, we can insert into the zero element efficiently
11667     // using a blend if we have AVX or AVX2 and the right data type.
11668     if (VT.is256BitVector() && IdxVal == 0) {
11669       // TODO: It is worthwhile to cast integer to floating point and back
11670       // and incur a domain crossing penalty if that's what we'll end up
11671       // doing anyway after extracting to a 128-bit vector.
11672       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11673           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11674         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11675         N2 = DAG.getIntPtrConstant(1, dl);
11676         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11677       }
11678     }
11679
11680     // Get the desired 128-bit vector chunk.
11681     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11682
11683     // Insert the element into the desired chunk.
11684     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11685     assert(isPowerOf2_32(NumEltsIn128));
11686     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11687     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11688
11689     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11690                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11691
11692     // Insert the changed part back into the bigger vector
11693     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11694   }
11695   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11696
11697   if (Subtarget->hasSSE41()) {
11698     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11699       unsigned Opc;
11700       if (VT == MVT::v8i16) {
11701         Opc = X86ISD::PINSRW;
11702       } else {
11703         assert(VT == MVT::v16i8);
11704         Opc = X86ISD::PINSRB;
11705       }
11706
11707       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11708       // argument.
11709       if (N1.getValueType() != MVT::i32)
11710         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11711       if (N2.getValueType() != MVT::i32)
11712         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11713       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11714     }
11715
11716     if (EltVT == MVT::f32) {
11717       // Bits [7:6] of the constant are the source select. This will always be
11718       //   zero here. The DAG Combiner may combine an extract_elt index into
11719       //   these bits. For example (insert (extract, 3), 2) could be matched by
11720       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11721       // Bits [5:4] of the constant are the destination select. This is the
11722       //   value of the incoming immediate.
11723       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11724       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11725
11726       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11727       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11728         // If this is an insertion of 32-bits into the low 32-bits of
11729         // a vector, we prefer to generate a blend with immediate rather
11730         // than an insertps. Blends are simpler operations in hardware and so
11731         // will always have equal or better performance than insertps.
11732         // But if optimizing for size and there's a load folding opportunity,
11733         // generate insertps because blendps does not have a 32-bit memory
11734         // operand form.
11735         N2 = DAG.getIntPtrConstant(1, dl);
11736         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11737         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11738       }
11739       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11740       // Create this as a scalar to vector..
11741       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11742       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11743     }
11744
11745     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11746       // PINSR* works with constant index.
11747       return Op;
11748     }
11749   }
11750
11751   if (EltVT == MVT::i8)
11752     return SDValue();
11753
11754   if (EltVT.getSizeInBits() == 16) {
11755     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11756     // as its second argument.
11757     if (N1.getValueType() != MVT::i32)
11758       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11759     if (N2.getValueType() != MVT::i32)
11760       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11761     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11762   }
11763   return SDValue();
11764 }
11765
11766 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11767   SDLoc dl(Op);
11768   MVT OpVT = Op.getSimpleValueType();
11769
11770   // If this is a 256-bit vector result, first insert into a 128-bit
11771   // vector and then insert into the 256-bit vector.
11772   if (!OpVT.is128BitVector()) {
11773     // Insert into a 128-bit vector.
11774     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11775     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11776                                  OpVT.getVectorNumElements() / SizeFactor);
11777
11778     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11779
11780     // Insert the 128-bit vector.
11781     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11782   }
11783
11784   if (OpVT == MVT::v1i64 &&
11785       Op.getOperand(0).getValueType() == MVT::i64)
11786     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11787
11788   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11789   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11790   return DAG.getBitcast(
11791       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11792 }
11793
11794 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11795 // a simple subregister reference or explicit instructions to grab
11796 // upper bits of a vector.
11797 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11798                                       SelectionDAG &DAG) {
11799   SDLoc dl(Op);
11800   SDValue In =  Op.getOperand(0);
11801   SDValue Idx = Op.getOperand(1);
11802   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11803   MVT ResVT   = Op.getSimpleValueType();
11804   MVT InVT    = In.getSimpleValueType();
11805
11806   if (Subtarget->hasFp256()) {
11807     if (ResVT.is128BitVector() &&
11808         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11809         isa<ConstantSDNode>(Idx)) {
11810       return Extract128BitVector(In, IdxVal, DAG, dl);
11811     }
11812     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11813         isa<ConstantSDNode>(Idx)) {
11814       return Extract256BitVector(In, IdxVal, DAG, dl);
11815     }
11816   }
11817   return SDValue();
11818 }
11819
11820 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11821 // simple superregister reference or explicit instructions to insert
11822 // the upper bits of a vector.
11823 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11824                                      SelectionDAG &DAG) {
11825   if (!Subtarget->hasAVX())
11826     return SDValue();
11827
11828   SDLoc dl(Op);
11829   SDValue Vec = Op.getOperand(0);
11830   SDValue SubVec = Op.getOperand(1);
11831   SDValue Idx = Op.getOperand(2);
11832
11833   if (!isa<ConstantSDNode>(Idx))
11834     return SDValue();
11835
11836   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11837   MVT OpVT = Op.getSimpleValueType();
11838   MVT SubVecVT = SubVec.getSimpleValueType();
11839
11840   // Fold two 16-byte subvector loads into one 32-byte load:
11841   // (insert_subvector (insert_subvector undef, (load addr), 0),
11842   //                   (load addr + 16), Elts/2)
11843   // --> load32 addr
11844   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11845       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11846       OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11847     auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11848     if (Idx2 && Idx2->getZExtValue() == 0) {
11849       SDValue SubVec2 = Vec.getOperand(1);
11850       // If needed, look through a bitcast to get to the load.
11851       if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11852         SubVec2 = SubVec2.getOperand(0);
11853
11854       if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11855         bool Fast;
11856         unsigned Alignment = FirstLd->getAlignment();
11857         unsigned AS = FirstLd->getAddressSpace();
11858         const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11859         if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11860                                     OpVT, AS, Alignment, &Fast) && Fast) {
11861           SDValue Ops[] = { SubVec2, SubVec };
11862           if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11863             return Ld;
11864         }
11865       }
11866     }
11867   }
11868
11869   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11870       SubVecVT.is128BitVector())
11871     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11872
11873   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11874     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11875
11876   if (OpVT.getVectorElementType() == MVT::i1)
11877     return Insert1BitVector(Op, DAG);
11878
11879   return SDValue();
11880 }
11881
11882 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11883 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11884 // one of the above mentioned nodes. It has to be wrapped because otherwise
11885 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11886 // be used to form addressing mode. These wrapped nodes will be selected
11887 // into MOV32ri.
11888 SDValue
11889 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11890   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11891
11892   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11893   // global base reg.
11894   unsigned char OpFlag = 0;
11895   unsigned WrapperKind = X86ISD::Wrapper;
11896   CodeModel::Model M = DAG.getTarget().getCodeModel();
11897
11898   if (Subtarget->isPICStyleRIPRel() &&
11899       (M == CodeModel::Small || M == CodeModel::Kernel))
11900     WrapperKind = X86ISD::WrapperRIP;
11901   else if (Subtarget->isPICStyleGOT())
11902     OpFlag = X86II::MO_GOTOFF;
11903   else if (Subtarget->isPICStyleStubPIC())
11904     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11905
11906   auto PtrVT = getPointerTy(DAG.getDataLayout());
11907   SDValue Result = DAG.getTargetConstantPool(
11908       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11909   SDLoc DL(CP);
11910   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11911   // With PIC, the address is actually $g + Offset.
11912   if (OpFlag) {
11913     Result =
11914         DAG.getNode(ISD::ADD, DL, PtrVT,
11915                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11916   }
11917
11918   return Result;
11919 }
11920
11921 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11922   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11923
11924   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11925   // global base reg.
11926   unsigned char OpFlag = 0;
11927   unsigned WrapperKind = X86ISD::Wrapper;
11928   CodeModel::Model M = DAG.getTarget().getCodeModel();
11929
11930   if (Subtarget->isPICStyleRIPRel() &&
11931       (M == CodeModel::Small || M == CodeModel::Kernel))
11932     WrapperKind = X86ISD::WrapperRIP;
11933   else if (Subtarget->isPICStyleGOT())
11934     OpFlag = X86II::MO_GOTOFF;
11935   else if (Subtarget->isPICStyleStubPIC())
11936     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11937
11938   auto PtrVT = getPointerTy(DAG.getDataLayout());
11939   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11940   SDLoc DL(JT);
11941   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11942
11943   // With PIC, the address is actually $g + Offset.
11944   if (OpFlag)
11945     Result =
11946         DAG.getNode(ISD::ADD, DL, PtrVT,
11947                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11948
11949   return Result;
11950 }
11951
11952 SDValue
11953 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11954   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11955
11956   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11957   // global base reg.
11958   unsigned char OpFlag = 0;
11959   unsigned WrapperKind = X86ISD::Wrapper;
11960   CodeModel::Model M = DAG.getTarget().getCodeModel();
11961
11962   if (Subtarget->isPICStyleRIPRel() &&
11963       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11964     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11965       OpFlag = X86II::MO_GOTPCREL;
11966     WrapperKind = X86ISD::WrapperRIP;
11967   } else if (Subtarget->isPICStyleGOT()) {
11968     OpFlag = X86II::MO_GOT;
11969   } else if (Subtarget->isPICStyleStubPIC()) {
11970     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11971   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11972     OpFlag = X86II::MO_DARWIN_NONLAZY;
11973   }
11974
11975   auto PtrVT = getPointerTy(DAG.getDataLayout());
11976   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11977
11978   SDLoc DL(Op);
11979   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11980
11981   // With PIC, the address is actually $g + Offset.
11982   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11983       !Subtarget->is64Bit()) {
11984     Result =
11985         DAG.getNode(ISD::ADD, DL, PtrVT,
11986                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11987   }
11988
11989   // For symbols that require a load from a stub to get the address, emit the
11990   // load.
11991   if (isGlobalStubReference(OpFlag))
11992     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11993                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11994                          false, false, false, 0);
11995
11996   return Result;
11997 }
11998
11999 SDValue
12000 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12001   // Create the TargetBlockAddressAddress node.
12002   unsigned char OpFlags =
12003     Subtarget->ClassifyBlockAddressReference();
12004   CodeModel::Model M = DAG.getTarget().getCodeModel();
12005   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12006   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12007   SDLoc dl(Op);
12008   auto PtrVT = getPointerTy(DAG.getDataLayout());
12009   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12010
12011   if (Subtarget->isPICStyleRIPRel() &&
12012       (M == CodeModel::Small || M == CodeModel::Kernel))
12013     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12014   else
12015     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12016
12017   // With PIC, the address is actually $g + Offset.
12018   if (isGlobalRelativeToPICBase(OpFlags)) {
12019     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12020                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12021   }
12022
12023   return Result;
12024 }
12025
12026 SDValue
12027 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12028                                       int64_t Offset, SelectionDAG &DAG) const {
12029   // Create the TargetGlobalAddress node, folding in the constant
12030   // offset if it is legal.
12031   unsigned char OpFlags =
12032       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12033   CodeModel::Model M = DAG.getTarget().getCodeModel();
12034   auto PtrVT = getPointerTy(DAG.getDataLayout());
12035   SDValue Result;
12036   if (OpFlags == X86II::MO_NO_FLAG &&
12037       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12038     // A direct static reference to a global.
12039     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12040     Offset = 0;
12041   } else {
12042     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12043   }
12044
12045   if (Subtarget->isPICStyleRIPRel() &&
12046       (M == CodeModel::Small || M == CodeModel::Kernel))
12047     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12048   else
12049     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12050
12051   // With PIC, the address is actually $g + Offset.
12052   if (isGlobalRelativeToPICBase(OpFlags)) {
12053     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12054                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12055   }
12056
12057   // For globals that require a load from a stub to get the address, emit the
12058   // load.
12059   if (isGlobalStubReference(OpFlags))
12060     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12061                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12062                          false, false, false, 0);
12063
12064   // If there was a non-zero offset that we didn't fold, create an explicit
12065   // addition for it.
12066   if (Offset != 0)
12067     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12068                          DAG.getConstant(Offset, dl, PtrVT));
12069
12070   return Result;
12071 }
12072
12073 SDValue
12074 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12075   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12076   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12077   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12078 }
12079
12080 static SDValue
12081 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12082            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12083            unsigned char OperandFlags, bool LocalDynamic = false) {
12084   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12085   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12086   SDLoc dl(GA);
12087   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12088                                            GA->getValueType(0),
12089                                            GA->getOffset(),
12090                                            OperandFlags);
12091
12092   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12093                                            : X86ISD::TLSADDR;
12094
12095   if (InFlag) {
12096     SDValue Ops[] = { Chain,  TGA, *InFlag };
12097     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12098   } else {
12099     SDValue Ops[]  = { Chain, TGA };
12100     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12101   }
12102
12103   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12104   MFI->setAdjustsStack(true);
12105   MFI->setHasCalls(true);
12106
12107   SDValue Flag = Chain.getValue(1);
12108   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12109 }
12110
12111 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12112 static SDValue
12113 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12114                                 const EVT PtrVT) {
12115   SDValue InFlag;
12116   SDLoc dl(GA);  // ? function entry point might be better
12117   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12118                                    DAG.getNode(X86ISD::GlobalBaseReg,
12119                                                SDLoc(), PtrVT), InFlag);
12120   InFlag = Chain.getValue(1);
12121
12122   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12123 }
12124
12125 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12126 static SDValue
12127 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12128                                 const EVT PtrVT) {
12129   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12130                     X86::RAX, X86II::MO_TLSGD);
12131 }
12132
12133 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12134                                            SelectionDAG &DAG,
12135                                            const EVT PtrVT,
12136                                            bool is64Bit) {
12137   SDLoc dl(GA);
12138
12139   // Get the start address of the TLS block for this module.
12140   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12141       .getInfo<X86MachineFunctionInfo>();
12142   MFI->incNumLocalDynamicTLSAccesses();
12143
12144   SDValue Base;
12145   if (is64Bit) {
12146     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12147                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12148   } else {
12149     SDValue InFlag;
12150     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12151         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12152     InFlag = Chain.getValue(1);
12153     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12154                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12155   }
12156
12157   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12158   // of Base.
12159
12160   // Build x@dtpoff.
12161   unsigned char OperandFlags = X86II::MO_DTPOFF;
12162   unsigned WrapperKind = X86ISD::Wrapper;
12163   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12164                                            GA->getValueType(0),
12165                                            GA->getOffset(), OperandFlags);
12166   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12167
12168   // Add x@dtpoff with the base.
12169   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12170 }
12171
12172 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12173 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12174                                    const EVT PtrVT, TLSModel::Model model,
12175                                    bool is64Bit, bool isPIC) {
12176   SDLoc dl(GA);
12177
12178   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12179   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12180                                                          is64Bit ? 257 : 256));
12181
12182   SDValue ThreadPointer =
12183       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12184                   MachinePointerInfo(Ptr), false, false, false, 0);
12185
12186   unsigned char OperandFlags = 0;
12187   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12188   // initialexec.
12189   unsigned WrapperKind = X86ISD::Wrapper;
12190   if (model == TLSModel::LocalExec) {
12191     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12192   } else if (model == TLSModel::InitialExec) {
12193     if (is64Bit) {
12194       OperandFlags = X86II::MO_GOTTPOFF;
12195       WrapperKind = X86ISD::WrapperRIP;
12196     } else {
12197       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12198     }
12199   } else {
12200     llvm_unreachable("Unexpected model");
12201   }
12202
12203   // emit "addl x@ntpoff,%eax" (local exec)
12204   // or "addl x@indntpoff,%eax" (initial exec)
12205   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12206   SDValue TGA =
12207       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12208                                  GA->getOffset(), OperandFlags);
12209   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12210
12211   if (model == TLSModel::InitialExec) {
12212     if (isPIC && !is64Bit) {
12213       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12214                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12215                            Offset);
12216     }
12217
12218     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12219                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12220                          false, false, false, 0);
12221   }
12222
12223   // The address of the thread local variable is the add of the thread
12224   // pointer with the offset of the variable.
12225   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12226 }
12227
12228 SDValue
12229 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12230
12231   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12232   const GlobalValue *GV = GA->getGlobal();
12233   auto PtrVT = getPointerTy(DAG.getDataLayout());
12234
12235   if (Subtarget->isTargetELF()) {
12236     if (DAG.getTarget().Options.EmulatedTLS)
12237       return LowerToTLSEmulatedModel(GA, DAG);
12238     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12239     switch (model) {
12240       case TLSModel::GeneralDynamic:
12241         if (Subtarget->is64Bit())
12242           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12243         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12244       case TLSModel::LocalDynamic:
12245         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12246                                            Subtarget->is64Bit());
12247       case TLSModel::InitialExec:
12248       case TLSModel::LocalExec:
12249         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12250                                    DAG.getTarget().getRelocationModel() ==
12251                                        Reloc::PIC_);
12252     }
12253     llvm_unreachable("Unknown TLS model.");
12254   }
12255
12256   if (Subtarget->isTargetDarwin()) {
12257     // Darwin only has one model of TLS.  Lower to that.
12258     unsigned char OpFlag = 0;
12259     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12260                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12261
12262     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12263     // global base reg.
12264     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12265                  !Subtarget->is64Bit();
12266     if (PIC32)
12267       OpFlag = X86II::MO_TLVP_PIC_BASE;
12268     else
12269       OpFlag = X86II::MO_TLVP;
12270     SDLoc DL(Op);
12271     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12272                                                 GA->getValueType(0),
12273                                                 GA->getOffset(), OpFlag);
12274     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12275
12276     // With PIC32, the address is actually $g + Offset.
12277     if (PIC32)
12278       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12279                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12280                            Offset);
12281
12282     // Lowering the machine isd will make sure everything is in the right
12283     // location.
12284     SDValue Chain = DAG.getEntryNode();
12285     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12286     SDValue Args[] = { Chain, Offset };
12287     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12288
12289     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12290     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12291     MFI->setAdjustsStack(true);
12292
12293     // And our return value (tls address) is in the standard call return value
12294     // location.
12295     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12296     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12297   }
12298
12299   if (Subtarget->isTargetKnownWindowsMSVC() ||
12300       Subtarget->isTargetWindowsGNU()) {
12301     // Just use the implicit TLS architecture
12302     // Need to generate someting similar to:
12303     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12304     //                                  ; from TEB
12305     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12306     //   mov     rcx, qword [rdx+rcx*8]
12307     //   mov     eax, .tls$:tlsvar
12308     //   [rax+rcx] contains the address
12309     // Windows 64bit: gs:0x58
12310     // Windows 32bit: fs:__tls_array
12311
12312     SDLoc dl(GA);
12313     SDValue Chain = DAG.getEntryNode();
12314
12315     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12316     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12317     // use its literal value of 0x2C.
12318     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12319                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12320                                                              256)
12321                                         : Type::getInt32PtrTy(*DAG.getContext(),
12322                                                               257));
12323
12324     SDValue TlsArray = Subtarget->is64Bit()
12325                            ? DAG.getIntPtrConstant(0x58, dl)
12326                            : (Subtarget->isTargetWindowsGNU()
12327                                   ? DAG.getIntPtrConstant(0x2C, dl)
12328                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
12329
12330     SDValue ThreadPointer =
12331         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12332                     false, false, 0);
12333
12334     SDValue res;
12335     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12336       res = ThreadPointer;
12337     } else {
12338       // Load the _tls_index variable
12339       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12340       if (Subtarget->is64Bit())
12341         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12342                              MachinePointerInfo(), MVT::i32, false, false,
12343                              false, 0);
12344       else
12345         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12346                           false, false, 0);
12347
12348       auto &DL = DAG.getDataLayout();
12349       SDValue Scale =
12350           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12351       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12352
12353       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12354     }
12355
12356     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12357                       false, 0);
12358
12359     // Get the offset of start of .tls section
12360     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12361                                              GA->getValueType(0),
12362                                              GA->getOffset(), X86II::MO_SECREL);
12363     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12364
12365     // The address of the thread local variable is the add of the thread
12366     // pointer with the offset of the variable.
12367     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12368   }
12369
12370   llvm_unreachable("TLS not implemented for this target.");
12371 }
12372
12373 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12374 /// and take a 2 x i32 value to shift plus a shift amount.
12375 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12376   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12377   MVT VT = Op.getSimpleValueType();
12378   unsigned VTBits = VT.getSizeInBits();
12379   SDLoc dl(Op);
12380   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12381   SDValue ShOpLo = Op.getOperand(0);
12382   SDValue ShOpHi = Op.getOperand(1);
12383   SDValue ShAmt  = Op.getOperand(2);
12384   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12385   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12386   // during isel.
12387   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12388                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
12389   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12390                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
12391                        : DAG.getConstant(0, dl, VT);
12392
12393   SDValue Tmp2, Tmp3;
12394   if (Op.getOpcode() == ISD::SHL_PARTS) {
12395     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12396     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12397   } else {
12398     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12399     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12400   }
12401
12402   // If the shift amount is larger or equal than the width of a part we can't
12403   // rely on the results of shld/shrd. Insert a test and select the appropriate
12404   // values for large shift amounts.
12405   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12406                                 DAG.getConstant(VTBits, dl, MVT::i8));
12407   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12408                              AndNode, DAG.getConstant(0, dl, MVT::i8));
12409
12410   SDValue Hi, Lo;
12411   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12412   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12413   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12414
12415   if (Op.getOpcode() == ISD::SHL_PARTS) {
12416     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12417     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12418   } else {
12419     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12420     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12421   }
12422
12423   SDValue Ops[2] = { Lo, Hi };
12424   return DAG.getMergeValues(Ops, dl);
12425 }
12426
12427 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12428                                            SelectionDAG &DAG) const {
12429   SDValue Src = Op.getOperand(0);
12430   MVT SrcVT = Src.getSimpleValueType();
12431   MVT VT = Op.getSimpleValueType();
12432   SDLoc dl(Op);
12433
12434   if (SrcVT.isVector()) {
12435     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12436       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12437                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12438                          DAG.getUNDEF(SrcVT)));
12439     }
12440     if (SrcVT.getVectorElementType() == MVT::i1) {
12441       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12442       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12443                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12444     }
12445     return SDValue();
12446   }
12447
12448   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12449          "Unknown SINT_TO_FP to lower!");
12450
12451   // These are really Legal; return the operand so the caller accepts it as
12452   // Legal.
12453   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12454     return Op;
12455   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12456       Subtarget->is64Bit()) {
12457     return Op;
12458   }
12459
12460   unsigned Size = SrcVT.getSizeInBits()/8;
12461   MachineFunction &MF = DAG.getMachineFunction();
12462   auto PtrVT = getPointerTy(MF.getDataLayout());
12463   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12464   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12465   SDValue Chain = DAG.getStore(
12466       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12467       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12468       false, 0);
12469   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12470 }
12471
12472 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12473                                      SDValue StackSlot,
12474                                      SelectionDAG &DAG) const {
12475   // Build the FILD
12476   SDLoc DL(Op);
12477   SDVTList Tys;
12478   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12479   if (useSSE)
12480     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12481   else
12482     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12483
12484   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12485
12486   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12487   MachineMemOperand *MMO;
12488   if (FI) {
12489     int SSFI = FI->getIndex();
12490     MMO = DAG.getMachineFunction().getMachineMemOperand(
12491         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12492         MachineMemOperand::MOLoad, ByteSize, ByteSize);
12493   } else {
12494     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12495     StackSlot = StackSlot.getOperand(1);
12496   }
12497   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12498   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12499                                            X86ISD::FILD, DL,
12500                                            Tys, Ops, SrcVT, MMO);
12501
12502   if (useSSE) {
12503     Chain = Result.getValue(1);
12504     SDValue InFlag = Result.getValue(2);
12505
12506     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12507     // shouldn't be necessary except that RFP cannot be live across
12508     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12509     MachineFunction &MF = DAG.getMachineFunction();
12510     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12511     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12512     auto PtrVT = getPointerTy(MF.getDataLayout());
12513     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12514     Tys = DAG.getVTList(MVT::Other);
12515     SDValue Ops[] = {
12516       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12517     };
12518     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12519         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12520         MachineMemOperand::MOStore, SSFISize, SSFISize);
12521
12522     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12523                                     Ops, Op.getValueType(), MMO);
12524     Result = DAG.getLoad(
12525         Op.getValueType(), DL, Chain, StackSlot,
12526         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12527         false, false, false, 0);
12528   }
12529
12530   return Result;
12531 }
12532
12533 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12534 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12535                                                SelectionDAG &DAG) const {
12536   // This algorithm is not obvious. Here it is what we're trying to output:
12537   /*
12538      movq       %rax,  %xmm0
12539      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12540      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12541      #ifdef __SSE3__
12542        haddpd   %xmm0, %xmm0
12543      #else
12544        pshufd   $0x4e, %xmm0, %xmm1
12545        addpd    %xmm1, %xmm0
12546      #endif
12547   */
12548
12549   SDLoc dl(Op);
12550   LLVMContext *Context = DAG.getContext();
12551
12552   // Build some magic constants.
12553   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12554   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12555   auto PtrVT = getPointerTy(DAG.getDataLayout());
12556   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12557
12558   SmallVector<Constant*,2> CV1;
12559   CV1.push_back(
12560     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12561                                       APInt(64, 0x4330000000000000ULL))));
12562   CV1.push_back(
12563     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12564                                       APInt(64, 0x4530000000000000ULL))));
12565   Constant *C1 = ConstantVector::get(CV1);
12566   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12567
12568   // Load the 64-bit value into an XMM register.
12569   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12570                             Op.getOperand(0));
12571   SDValue CLod0 =
12572       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12573                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12574                   false, false, false, 16);
12575   SDValue Unpck1 =
12576       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12577
12578   SDValue CLod1 =
12579       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12580                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12581                   false, false, false, 16);
12582   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12583   // TODO: Are there any fast-math-flags to propagate here?
12584   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12585   SDValue Result;
12586
12587   if (Subtarget->hasSSE3()) {
12588     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12589     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12590   } else {
12591     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12592     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12593                                            S2F, 0x4E, DAG);
12594     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12595                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12596   }
12597
12598   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12599                      DAG.getIntPtrConstant(0, dl));
12600 }
12601
12602 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12603 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12604                                                SelectionDAG &DAG) const {
12605   SDLoc dl(Op);
12606   // FP constant to bias correct the final result.
12607   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12608                                    MVT::f64);
12609
12610   // Load the 32-bit value into an XMM register.
12611   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12612                              Op.getOperand(0));
12613
12614   // Zero out the upper parts of the register.
12615   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12616
12617   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12618                      DAG.getBitcast(MVT::v2f64, Load),
12619                      DAG.getIntPtrConstant(0, dl));
12620
12621   // Or the load with the bias.
12622   SDValue Or = DAG.getNode(
12623       ISD::OR, dl, MVT::v2i64,
12624       DAG.getBitcast(MVT::v2i64,
12625                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12626       DAG.getBitcast(MVT::v2i64,
12627                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12628   Or =
12629       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12630                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12631
12632   // Subtract the bias.
12633   // TODO: Are there any fast-math-flags to propagate here?
12634   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12635
12636   // Handle final rounding.
12637   MVT DestVT = Op.getSimpleValueType();
12638
12639   if (DestVT.bitsLT(MVT::f64))
12640     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12641                        DAG.getIntPtrConstant(0, dl));
12642   if (DestVT.bitsGT(MVT::f64))
12643     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12644
12645   // Handle final rounding.
12646   return Sub;
12647 }
12648
12649 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12650                                      const X86Subtarget &Subtarget) {
12651   // The algorithm is the following:
12652   // #ifdef __SSE4_1__
12653   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12654   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12655   //                                 (uint4) 0x53000000, 0xaa);
12656   // #else
12657   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12658   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12659   // #endif
12660   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12661   //     return (float4) lo + fhi;
12662
12663   // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12664   // reassociate the two FADDs, and if we do that, the algorithm fails
12665   // spectacularly (PR24512).
12666   // FIXME: If we ever have some kind of Machine FMF, this should be marked
12667   // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12668   // there's also the MachineCombiner reassociations happening on Machine IR.
12669   if (DAG.getTarget().Options.UnsafeFPMath)
12670     return SDValue();
12671
12672   SDLoc DL(Op);
12673   SDValue V = Op->getOperand(0);
12674   MVT VecIntVT = V.getSimpleValueType();
12675   bool Is128 = VecIntVT == MVT::v4i32;
12676   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12677   // If we convert to something else than the supported type, e.g., to v4f64,
12678   // abort early.
12679   if (VecFloatVT != Op->getSimpleValueType(0))
12680     return SDValue();
12681
12682   unsigned NumElts = VecIntVT.getVectorNumElements();
12683   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12684          "Unsupported custom type");
12685   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12686
12687   // In the #idef/#else code, we have in common:
12688   // - The vector of constants:
12689   // -- 0x4b000000
12690   // -- 0x53000000
12691   // - A shift:
12692   // -- v >> 16
12693
12694   // Create the splat vector for 0x4b000000.
12695   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12696   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12697                            CstLow, CstLow, CstLow, CstLow};
12698   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12699                                   makeArrayRef(&CstLowArray[0], NumElts));
12700   // Create the splat vector for 0x53000000.
12701   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12702   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12703                             CstHigh, CstHigh, CstHigh, CstHigh};
12704   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12705                                    makeArrayRef(&CstHighArray[0], NumElts));
12706
12707   // Create the right shift.
12708   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12709   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12710                              CstShift, CstShift, CstShift, CstShift};
12711   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12712                                     makeArrayRef(&CstShiftArray[0], NumElts));
12713   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12714
12715   SDValue Low, High;
12716   if (Subtarget.hasSSE41()) {
12717     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12718     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12719     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12720     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12721     // Low will be bitcasted right away, so do not bother bitcasting back to its
12722     // original type.
12723     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12724                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12725     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12726     //                                 (uint4) 0x53000000, 0xaa);
12727     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12728     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12729     // High will be bitcasted right away, so do not bother bitcasting back to
12730     // its original type.
12731     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12732                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12733   } else {
12734     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12735     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12736                                      CstMask, CstMask, CstMask);
12737     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12738     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12739     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12740
12741     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12742     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12743   }
12744
12745   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12746   SDValue CstFAdd = DAG.getConstantFP(
12747       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12748   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12749                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12750   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12751                                    makeArrayRef(&CstFAddArray[0], NumElts));
12752
12753   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12754   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12755   // TODO: Are there any fast-math-flags to propagate here?
12756   SDValue FHigh =
12757       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12758   //     return (float4) lo + fhi;
12759   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12760   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12761 }
12762
12763 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12764                                                SelectionDAG &DAG) const {
12765   SDValue N0 = Op.getOperand(0);
12766   MVT SVT = N0.getSimpleValueType();
12767   SDLoc dl(Op);
12768
12769   switch (SVT.SimpleTy) {
12770   default:
12771     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12772   case MVT::v4i8:
12773   case MVT::v4i16:
12774   case MVT::v8i8:
12775   case MVT::v8i16: {
12776     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12777     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12778                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12779   }
12780   case MVT::v4i32:
12781   case MVT::v8i32:
12782     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12783   case MVT::v16i8:
12784   case MVT::v16i16:
12785     assert(Subtarget->hasAVX512());
12786     return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12787                        DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12788   }
12789 }
12790
12791 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12792                                            SelectionDAG &DAG) const {
12793   SDValue N0 = Op.getOperand(0);
12794   SDLoc dl(Op);
12795   auto PtrVT = getPointerTy(DAG.getDataLayout());
12796
12797   if (Op.getSimpleValueType().isVector())
12798     return lowerUINT_TO_FP_vec(Op, DAG);
12799
12800   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12801   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12802   // the optimization here.
12803   if (DAG.SignBitIsZero(N0))
12804     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12805
12806   MVT SrcVT = N0.getSimpleValueType();
12807   MVT DstVT = Op.getSimpleValueType();
12808
12809   if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12810       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12811     // Conversions from unsigned i32 to f32/f64 are legal,
12812     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
12813     return Op;
12814   }
12815
12816   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12817     return LowerUINT_TO_FP_i64(Op, DAG);
12818   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12819     return LowerUINT_TO_FP_i32(Op, DAG);
12820   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12821     return SDValue();
12822
12823   // Make a 64-bit buffer, and use it to build an FILD.
12824   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12825   if (SrcVT == MVT::i32) {
12826     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12827     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12828     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12829                                   StackSlot, MachinePointerInfo(),
12830                                   false, false, 0);
12831     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12832                                   OffsetSlot, MachinePointerInfo(),
12833                                   false, false, 0);
12834     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12835     return Fild;
12836   }
12837
12838   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12839   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12840                                StackSlot, MachinePointerInfo(),
12841                                false, false, 0);
12842   // For i64 source, we need to add the appropriate power of 2 if the input
12843   // was negative.  This is the same as the optimization in
12844   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12845   // we must be careful to do the computation in x87 extended precision, not
12846   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12847   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12848   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12849       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12850       MachineMemOperand::MOLoad, 8, 8);
12851
12852   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12853   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12854   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12855                                          MVT::i64, MMO);
12856
12857   APInt FF(32, 0x5F800000ULL);
12858
12859   // Check whether the sign bit is set.
12860   SDValue SignSet = DAG.getSetCC(
12861       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12862       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12863
12864   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12865   SDValue FudgePtr = DAG.getConstantPool(
12866       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12867
12868   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12869   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12870   SDValue Four = DAG.getIntPtrConstant(4, dl);
12871   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12872                                Zero, Four);
12873   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12874
12875   // Load the value out, extending it from f32 to f80.
12876   // FIXME: Avoid the extend by constructing the right constant pool?
12877   SDValue Fudge = DAG.getExtLoad(
12878       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12879       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12880       false, false, false, 4);
12881   // Extend everything to 80 bits to force it to be done on x87.
12882   // TODO: Are there any fast-math-flags to propagate here?
12883   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12884   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12885                      DAG.getIntPtrConstant(0, dl));
12886 }
12887
12888 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12889 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12890 // just return an <SDValue(), SDValue()> pair.
12891 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12892 // to i16, i32 or i64, and we lower it to a legal sequence.
12893 // If lowered to the final integer result we return a <result, SDValue()> pair.
12894 // Otherwise we lower it to a sequence ending with a FIST, return a
12895 // <FIST, StackSlot> pair, and the caller is responsible for loading
12896 // the final integer result from StackSlot.
12897 std::pair<SDValue,SDValue>
12898 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12899                                    bool IsSigned, bool IsReplace) const {
12900   SDLoc DL(Op);
12901
12902   EVT DstTy = Op.getValueType();
12903   EVT TheVT = Op.getOperand(0).getValueType();
12904   auto PtrVT = getPointerTy(DAG.getDataLayout());
12905
12906   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12907     // f16 must be promoted before using the lowering in this routine.
12908     // fp128 does not use this lowering.
12909     return std::make_pair(SDValue(), SDValue());
12910   }
12911
12912   // If using FIST to compute an unsigned i64, we'll need some fixup
12913   // to handle values above the maximum signed i64.  A FIST is always
12914   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12915   bool UnsignedFixup = !IsSigned &&
12916                        DstTy == MVT::i64 &&
12917                        (!Subtarget->is64Bit() ||
12918                         !isScalarFPTypeInSSEReg(TheVT));
12919
12920   if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12921     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12922     // The low 32 bits of the fist result will have the correct uint32 result.
12923     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12924     DstTy = MVT::i64;
12925   }
12926
12927   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12928          DstTy.getSimpleVT() >= MVT::i16 &&
12929          "Unknown FP_TO_INT to lower!");
12930
12931   // These are really Legal.
12932   if (DstTy == MVT::i32 &&
12933       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12934     return std::make_pair(SDValue(), SDValue());
12935   if (Subtarget->is64Bit() &&
12936       DstTy == MVT::i64 &&
12937       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12938     return std::make_pair(SDValue(), SDValue());
12939
12940   // We lower FP->int64 into FISTP64 followed by a load from a temporary
12941   // stack slot.
12942   MachineFunction &MF = DAG.getMachineFunction();
12943   unsigned MemSize = DstTy.getSizeInBits()/8;
12944   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12945   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12946
12947   unsigned Opc;
12948   switch (DstTy.getSimpleVT().SimpleTy) {
12949   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12950   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12951   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12952   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12953   }
12954
12955   SDValue Chain = DAG.getEntryNode();
12956   SDValue Value = Op.getOperand(0);
12957   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12958
12959   if (UnsignedFixup) {
12960     //
12961     // Conversion to unsigned i64 is implemented with a select,
12962     // depending on whether the source value fits in the range
12963     // of a signed i64.  Let Thresh be the FP equivalent of
12964     // 0x8000000000000000ULL.
12965     //
12966     //  Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12967     //  FistSrc    = (Value < Thresh) ? Value : (Value - Thresh);
12968     //  Fist-to-mem64 FistSrc
12969     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12970     //  to XOR'ing the high 32 bits with Adjust.
12971     //
12972     // Being a power of 2, Thresh is exactly representable in all FP formats.
12973     // For X87 we'd like to use the smallest FP type for this constant, but
12974     // for DAG type consistency we have to match the FP operand type.
12975
12976     APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12977     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
12978     bool LosesInfo = false;
12979     if (TheVT == MVT::f64)
12980       // The rounding mode is irrelevant as the conversion should be exact.
12981       Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12982                               &LosesInfo);
12983     else if (TheVT == MVT::f80)
12984       Status = Thresh.convert(APFloat::x87DoubleExtended,
12985                               APFloat::rmNearestTiesToEven, &LosesInfo);
12986
12987     assert(Status == APFloat::opOK && !LosesInfo &&
12988            "FP conversion should have been exact");
12989
12990     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12991
12992     SDValue Cmp = DAG.getSetCC(DL,
12993                                getSetCCResultType(DAG.getDataLayout(),
12994                                                   *DAG.getContext(), TheVT),
12995                                Value, ThreshVal, ISD::SETLT);
12996     Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12997                            DAG.getConstant(0, DL, MVT::i32),
12998                            DAG.getConstant(0x80000000, DL, MVT::i32));
12999     SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13000     Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13001                                               *DAG.getContext(), TheVT),
13002                        Value, ThreshVal, ISD::SETLT);
13003     Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13004   }
13005
13006   // FIXME This causes a redundant load/store if the SSE-class value is already
13007   // in memory, such as if it is on the callstack.
13008   if (isScalarFPTypeInSSEReg(TheVT)) {
13009     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13010     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13011                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
13012                          false, 0);
13013     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13014     SDValue Ops[] = {
13015       Chain, StackSlot, DAG.getValueType(TheVT)
13016     };
13017
13018     MachineMemOperand *MMO =
13019         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13020                                 MachineMemOperand::MOLoad, MemSize, MemSize);
13021     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13022     Chain = Value.getValue(1);
13023     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13024     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13025   }
13026
13027   MachineMemOperand *MMO =
13028       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13029                               MachineMemOperand::MOStore, MemSize, MemSize);
13030
13031   if (UnsignedFixup) {
13032
13033     // Insert the FIST, load its result as two i32's,
13034     // and XOR the high i32 with Adjust.
13035
13036     SDValue FistOps[] = { Chain, Value, StackSlot };
13037     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13038                                            FistOps, DstTy, MMO);
13039
13040     SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13041                                 MachinePointerInfo(),
13042                                 false, false, false, 0);
13043     SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13044                                    DAG.getConstant(4, DL, PtrVT));
13045
13046     SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13047                                  MachinePointerInfo(),
13048                                  false, false, false, 0);
13049     High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13050
13051     if (Subtarget->is64Bit()) {
13052       // Join High32 and Low32 into a 64-bit result.
13053       // (High32 << 32) | Low32
13054       Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13055       High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13056       High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13057                            DAG.getConstant(32, DL, MVT::i8));
13058       SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13059       return std::make_pair(Result, SDValue());
13060     }
13061
13062     SDValue ResultOps[] = { Low32, High32 };
13063
13064     SDValue pair = IsReplace
13065       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13066       : DAG.getMergeValues(ResultOps, DL);
13067     return std::make_pair(pair, SDValue());
13068   } else {
13069     // Build the FP_TO_INT*_IN_MEM
13070     SDValue Ops[] = { Chain, Value, StackSlot };
13071     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13072                                            Ops, DstTy, MMO);
13073     return std::make_pair(FIST, StackSlot);
13074   }
13075 }
13076
13077 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13078                               const X86Subtarget *Subtarget) {
13079   MVT VT = Op->getSimpleValueType(0);
13080   SDValue In = Op->getOperand(0);
13081   MVT InVT = In.getSimpleValueType();
13082   SDLoc dl(Op);
13083
13084   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13085     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13086
13087   // Optimize vectors in AVX mode:
13088   //
13089   //   v8i16 -> v8i32
13090   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
13091   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
13092   //   Concat upper and lower parts.
13093   //
13094   //   v4i32 -> v4i64
13095   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
13096   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
13097   //   Concat upper and lower parts.
13098   //
13099
13100   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13101       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13102       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13103     return SDValue();
13104
13105   if (Subtarget->hasInt256())
13106     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13107
13108   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13109   SDValue Undef = DAG.getUNDEF(InVT);
13110   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13111   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13112   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13113
13114   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13115                              VT.getVectorNumElements()/2);
13116
13117   OpLo = DAG.getBitcast(HVT, OpLo);
13118   OpHi = DAG.getBitcast(HVT, OpHi);
13119
13120   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13121 }
13122
13123 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13124                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13125   MVT VT = Op->getSimpleValueType(0);
13126   SDValue In = Op->getOperand(0);
13127   MVT InVT = In.getSimpleValueType();
13128   SDLoc DL(Op);
13129   unsigned int NumElts = VT.getVectorNumElements();
13130   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13131     return SDValue();
13132
13133   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13134     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13135
13136   assert(InVT.getVectorElementType() == MVT::i1);
13137   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13138   SDValue One =
13139    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13140   SDValue Zero =
13141    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13142
13143   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13144   if (VT.is512BitVector())
13145     return V;
13146   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13147 }
13148
13149 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13150                                SelectionDAG &DAG) {
13151   if (Subtarget->hasFp256())
13152     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13153       return Res;
13154
13155   return SDValue();
13156 }
13157
13158 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13159                                 SelectionDAG &DAG) {
13160   SDLoc DL(Op);
13161   MVT VT = Op.getSimpleValueType();
13162   SDValue In = Op.getOperand(0);
13163   MVT SVT = In.getSimpleValueType();
13164
13165   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13166     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13167
13168   if (Subtarget->hasFp256())
13169     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13170       return Res;
13171
13172   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13173          VT.getVectorNumElements() != SVT.getVectorNumElements());
13174   return SDValue();
13175 }
13176
13177 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13178   SDLoc DL(Op);
13179   MVT VT = Op.getSimpleValueType();
13180   SDValue In = Op.getOperand(0);
13181   MVT InVT = In.getSimpleValueType();
13182
13183   if (VT == MVT::i1) {
13184     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13185            "Invalid scalar TRUNCATE operation");
13186     if (InVT.getSizeInBits() >= 32)
13187       return SDValue();
13188     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13189     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13190   }
13191   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13192          "Invalid TRUNCATE operation");
13193
13194   // move vector to mask - truncate solution for SKX
13195   if (VT.getVectorElementType() == MVT::i1) {
13196     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13197         Subtarget->hasBWI())
13198       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13199     if ((InVT.is256BitVector() || InVT.is128BitVector())
13200         && InVT.getScalarSizeInBits() <= 16 &&
13201         Subtarget->hasBWI() && Subtarget->hasVLX())
13202       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13203     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13204         Subtarget->hasDQI())
13205       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13206     if ((InVT.is256BitVector() || InVT.is128BitVector())
13207         && InVT.getScalarSizeInBits() >= 32 &&
13208         Subtarget->hasDQI() && Subtarget->hasVLX())
13209       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13210   }
13211
13212   if (VT.getVectorElementType() == MVT::i1) {
13213     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13214     unsigned NumElts = InVT.getVectorNumElements();
13215     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13216     if (InVT.getSizeInBits() < 512) {
13217       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13218       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13219       InVT = ExtVT;
13220     }
13221
13222     SDValue OneV =
13223      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13224     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13225     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13226   }
13227
13228   // vpmovqb/w/d, vpmovdb/w, vpmovwb
13229   if (Subtarget->hasAVX512()) {
13230     // word to byte only under BWI
13231     if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13232       return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13233                          DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13234     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13235   }
13236   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13237     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13238     if (Subtarget->hasInt256()) {
13239       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13240       In = DAG.getBitcast(MVT::v8i32, In);
13241       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13242                                 ShufMask);
13243       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13244                          DAG.getIntPtrConstant(0, DL));
13245     }
13246
13247     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13248                                DAG.getIntPtrConstant(0, DL));
13249     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13250                                DAG.getIntPtrConstant(2, DL));
13251     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13252     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13253     static const int ShufMask[] = {0, 2, 4, 6};
13254     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13255   }
13256
13257   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13258     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13259     if (Subtarget->hasInt256()) {
13260       In = DAG.getBitcast(MVT::v32i8, In);
13261
13262       SmallVector<SDValue,32> pshufbMask;
13263       for (unsigned i = 0; i < 2; ++i) {
13264         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13265         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13266         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13267         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13268         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13269         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13270         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13271         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13272         for (unsigned j = 0; j < 8; ++j)
13273           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13274       }
13275       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13276       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13277       In = DAG.getBitcast(MVT::v4i64, In);
13278
13279       static const int ShufMask[] = {0,  2,  -1,  -1};
13280       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13281                                 &ShufMask[0]);
13282       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13283                        DAG.getIntPtrConstant(0, DL));
13284       return DAG.getBitcast(VT, In);
13285     }
13286
13287     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13288                                DAG.getIntPtrConstant(0, DL));
13289
13290     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13291                                DAG.getIntPtrConstant(4, DL));
13292
13293     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13294     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13295
13296     // The PSHUFB mask:
13297     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13298                                    -1, -1, -1, -1, -1, -1, -1, -1};
13299
13300     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13301     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13302     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13303
13304     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13305     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13306
13307     // The MOVLHPS Mask:
13308     static const int ShufMask2[] = {0, 1, 4, 5};
13309     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13310     return DAG.getBitcast(MVT::v8i16, res);
13311   }
13312
13313   // Handle truncation of V256 to V128 using shuffles.
13314   if (!VT.is128BitVector() || !InVT.is256BitVector())
13315     return SDValue();
13316
13317   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13318
13319   unsigned NumElems = VT.getVectorNumElements();
13320   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13321
13322   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13323   // Prepare truncation shuffle mask
13324   for (unsigned i = 0; i != NumElems; ++i)
13325     MaskVec[i] = i * 2;
13326   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13327                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13328   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13329                      DAG.getIntPtrConstant(0, DL));
13330 }
13331
13332 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13333                                            SelectionDAG &DAG) const {
13334   assert(!Op.getSimpleValueType().isVector());
13335
13336   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13337     /*IsSigned=*/ true, /*IsReplace=*/ false);
13338   SDValue FIST = Vals.first, StackSlot = Vals.second;
13339   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13340   if (!FIST.getNode())
13341     return Op;
13342
13343   if (StackSlot.getNode())
13344     // Load the result.
13345     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13346                        FIST, StackSlot, MachinePointerInfo(),
13347                        false, false, false, 0);
13348
13349   // The node is the result.
13350   return FIST;
13351 }
13352
13353 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13354                                            SelectionDAG &DAG) const {
13355   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13356     /*IsSigned=*/ false, /*IsReplace=*/ false);
13357   SDValue FIST = Vals.first, StackSlot = Vals.second;
13358   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13359   if (!FIST.getNode())
13360     return Op;
13361
13362   if (StackSlot.getNode())
13363     // Load the result.
13364     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13365                        FIST, StackSlot, MachinePointerInfo(),
13366                        false, false, false, 0);
13367
13368   // The node is the result.
13369   return FIST;
13370 }
13371
13372 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13373   SDLoc DL(Op);
13374   MVT VT = Op.getSimpleValueType();
13375   SDValue In = Op.getOperand(0);
13376   MVT SVT = In.getSimpleValueType();
13377
13378   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13379
13380   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13381                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13382                                  In, DAG.getUNDEF(SVT)));
13383 }
13384
13385 /// The only differences between FABS and FNEG are the mask and the logic op.
13386 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13387 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13388   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13389          "Wrong opcode for lowering FABS or FNEG.");
13390
13391   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13392
13393   // If this is a FABS and it has an FNEG user, bail out to fold the combination
13394   // into an FNABS. We'll lower the FABS after that if it is still in use.
13395   if (IsFABS)
13396     for (SDNode *User : Op->uses())
13397       if (User->getOpcode() == ISD::FNEG)
13398         return Op;
13399
13400   SDLoc dl(Op);
13401   MVT VT = Op.getSimpleValueType();
13402
13403   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13404   // decide if we should generate a 16-byte constant mask when we only need 4 or
13405   // 8 bytes for the scalar case.
13406
13407   MVT LogicVT;
13408   MVT EltVT;
13409   unsigned NumElts;
13410
13411   if (VT.isVector()) {
13412     LogicVT = VT;
13413     EltVT = VT.getVectorElementType();
13414     NumElts = VT.getVectorNumElements();
13415   } else {
13416     // There are no scalar bitwise logical SSE/AVX instructions, so we
13417     // generate a 16-byte vector constant and logic op even for the scalar case.
13418     // Using a 16-byte mask allows folding the load of the mask with
13419     // the logic op, so it can save (~4 bytes) on code size.
13420     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13421     EltVT = VT;
13422     NumElts = (VT == MVT::f64) ? 2 : 4;
13423   }
13424
13425   unsigned EltBits = EltVT.getSizeInBits();
13426   LLVMContext *Context = DAG.getContext();
13427   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13428   APInt MaskElt =
13429     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13430   Constant *C = ConstantInt::get(*Context, MaskElt);
13431   C = ConstantVector::getSplat(NumElts, C);
13432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13433   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13434   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13435   SDValue Mask =
13436       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13437                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13438                   false, false, false, Alignment);
13439
13440   SDValue Op0 = Op.getOperand(0);
13441   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13442   unsigned LogicOp =
13443     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13444   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13445
13446   if (VT.isVector())
13447     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13448
13449   // For the scalar case extend to a 128-bit vector, perform the logic op,
13450   // and extract the scalar result back out.
13451   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13452   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13453   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13454                      DAG.getIntPtrConstant(0, dl));
13455 }
13456
13457 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13459   LLVMContext *Context = DAG.getContext();
13460   SDValue Op0 = Op.getOperand(0);
13461   SDValue Op1 = Op.getOperand(1);
13462   SDLoc dl(Op);
13463   MVT VT = Op.getSimpleValueType();
13464   MVT SrcVT = Op1.getSimpleValueType();
13465
13466   // If second operand is smaller, extend it first.
13467   if (SrcVT.bitsLT(VT)) {
13468     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13469     SrcVT = VT;
13470   }
13471   // And if it is bigger, shrink it first.
13472   if (SrcVT.bitsGT(VT)) {
13473     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13474     SrcVT = VT;
13475   }
13476
13477   // At this point the operands and the result should have the same
13478   // type, and that won't be f80 since that is not custom lowered.
13479
13480   const fltSemantics &Sem =
13481       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13482   const unsigned SizeInBits = VT.getSizeInBits();
13483
13484   SmallVector<Constant *, 4> CV(
13485       VT == MVT::f64 ? 2 : 4,
13486       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13487
13488   // First, clear all bits but the sign bit from the second operand (sign).
13489   CV[0] = ConstantFP::get(*Context,
13490                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13491   Constant *C = ConstantVector::get(CV);
13492   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13493   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13494
13495   // Perform all logic operations as 16-byte vectors because there are no
13496   // scalar FP logic instructions in SSE. This allows load folding of the
13497   // constants into the logic instructions.
13498   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13499   SDValue Mask1 =
13500       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13501                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13502                   false, false, false, 16);
13503   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13504   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13505
13506   // Next, clear the sign bit from the first operand (magnitude).
13507   // If it's a constant, we can clear it here.
13508   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13509     APFloat APF = Op0CN->getValueAPF();
13510     // If the magnitude is a positive zero, the sign bit alone is enough.
13511     if (APF.isPosZero())
13512       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13513                          DAG.getIntPtrConstant(0, dl));
13514     APF.clearSign();
13515     CV[0] = ConstantFP::get(*Context, APF);
13516   } else {
13517     CV[0] = ConstantFP::get(
13518         *Context,
13519         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13520   }
13521   C = ConstantVector::get(CV);
13522   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13523   SDValue Val =
13524       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13525                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13526                   false, false, false, 16);
13527   // If the magnitude operand wasn't a constant, we need to AND out the sign.
13528   if (!isa<ConstantFPSDNode>(Op0)) {
13529     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13530     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13531   }
13532   // OR the magnitude value with the sign bit.
13533   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13534   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13535                      DAG.getIntPtrConstant(0, dl));
13536 }
13537
13538 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13539   SDValue N0 = Op.getOperand(0);
13540   SDLoc dl(Op);
13541   MVT VT = Op.getSimpleValueType();
13542
13543   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13544   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13545                                   DAG.getConstant(1, dl, VT));
13546   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13547 }
13548
13549 // Check whether an OR'd tree is PTEST-able.
13550 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13551                                       SelectionDAG &DAG) {
13552   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13553
13554   if (!Subtarget->hasSSE41())
13555     return SDValue();
13556
13557   if (!Op->hasOneUse())
13558     return SDValue();
13559
13560   SDNode *N = Op.getNode();
13561   SDLoc DL(N);
13562
13563   SmallVector<SDValue, 8> Opnds;
13564   DenseMap<SDValue, unsigned> VecInMap;
13565   SmallVector<SDValue, 8> VecIns;
13566   EVT VT = MVT::Other;
13567
13568   // Recognize a special case where a vector is casted into wide integer to
13569   // test all 0s.
13570   Opnds.push_back(N->getOperand(0));
13571   Opnds.push_back(N->getOperand(1));
13572
13573   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13574     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13575     // BFS traverse all OR'd operands.
13576     if (I->getOpcode() == ISD::OR) {
13577       Opnds.push_back(I->getOperand(0));
13578       Opnds.push_back(I->getOperand(1));
13579       // Re-evaluate the number of nodes to be traversed.
13580       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13581       continue;
13582     }
13583
13584     // Quit if a non-EXTRACT_VECTOR_ELT
13585     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13586       return SDValue();
13587
13588     // Quit if without a constant index.
13589     SDValue Idx = I->getOperand(1);
13590     if (!isa<ConstantSDNode>(Idx))
13591       return SDValue();
13592
13593     SDValue ExtractedFromVec = I->getOperand(0);
13594     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13595     if (M == VecInMap.end()) {
13596       VT = ExtractedFromVec.getValueType();
13597       // Quit if not 128/256-bit vector.
13598       if (!VT.is128BitVector() && !VT.is256BitVector())
13599         return SDValue();
13600       // Quit if not the same type.
13601       if (VecInMap.begin() != VecInMap.end() &&
13602           VT != VecInMap.begin()->first.getValueType())
13603         return SDValue();
13604       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13605       VecIns.push_back(ExtractedFromVec);
13606     }
13607     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13608   }
13609
13610   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13611          "Not extracted from 128-/256-bit vector.");
13612
13613   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13614
13615   for (DenseMap<SDValue, unsigned>::const_iterator
13616         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13617     // Quit if not all elements are used.
13618     if (I->second != FullMask)
13619       return SDValue();
13620   }
13621
13622   MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13623
13624   // Cast all vectors into TestVT for PTEST.
13625   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13626     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13627
13628   // If more than one full vectors are evaluated, OR them first before PTEST.
13629   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13630     // Each iteration will OR 2 nodes and append the result until there is only
13631     // 1 node left, i.e. the final OR'd value of all vectors.
13632     SDValue LHS = VecIns[Slot];
13633     SDValue RHS = VecIns[Slot + 1];
13634     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13635   }
13636
13637   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13638                      VecIns.back(), VecIns.back());
13639 }
13640
13641 /// \brief return true if \c Op has a use that doesn't just read flags.
13642 static bool hasNonFlagsUse(SDValue Op) {
13643   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13644        ++UI) {
13645     SDNode *User = *UI;
13646     unsigned UOpNo = UI.getOperandNo();
13647     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13648       // Look pass truncate.
13649       UOpNo = User->use_begin().getOperandNo();
13650       User = *User->use_begin();
13651     }
13652
13653     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13654         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13655       return true;
13656   }
13657   return false;
13658 }
13659
13660 /// Emit nodes that will be selected as "test Op0,Op0", or something
13661 /// equivalent.
13662 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13663                                     SelectionDAG &DAG) const {
13664   if (Op.getValueType() == MVT::i1) {
13665     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13666     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13667                        DAG.getConstant(0, dl, MVT::i8));
13668   }
13669   // CF and OF aren't always set the way we want. Determine which
13670   // of these we need.
13671   bool NeedCF = false;
13672   bool NeedOF = false;
13673   switch (X86CC) {
13674   default: break;
13675   case X86::COND_A: case X86::COND_AE:
13676   case X86::COND_B: case X86::COND_BE:
13677     NeedCF = true;
13678     break;
13679   case X86::COND_G: case X86::COND_GE:
13680   case X86::COND_L: case X86::COND_LE:
13681   case X86::COND_O: case X86::COND_NO: {
13682     // Check if we really need to set the
13683     // Overflow flag. If NoSignedWrap is present
13684     // that is not actually needed.
13685     switch (Op->getOpcode()) {
13686     case ISD::ADD:
13687     case ISD::SUB:
13688     case ISD::MUL:
13689     case ISD::SHL: {
13690       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13691       if (BinNode->Flags.hasNoSignedWrap())
13692         break;
13693     }
13694     default:
13695       NeedOF = true;
13696       break;
13697     }
13698     break;
13699   }
13700   }
13701   // See if we can use the EFLAGS value from the operand instead of
13702   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13703   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13704   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13705     // Emit a CMP with 0, which is the TEST pattern.
13706     //if (Op.getValueType() == MVT::i1)
13707     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13708     //                     DAG.getConstant(0, MVT::i1));
13709     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13710                        DAG.getConstant(0, dl, Op.getValueType()));
13711   }
13712   unsigned Opcode = 0;
13713   unsigned NumOperands = 0;
13714
13715   // Truncate operations may prevent the merge of the SETCC instruction
13716   // and the arithmetic instruction before it. Attempt to truncate the operands
13717   // of the arithmetic instruction and use a reduced bit-width instruction.
13718   bool NeedTruncation = false;
13719   SDValue ArithOp = Op;
13720   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13721     SDValue Arith = Op->getOperand(0);
13722     // Both the trunc and the arithmetic op need to have one user each.
13723     if (Arith->hasOneUse())
13724       switch (Arith.getOpcode()) {
13725         default: break;
13726         case ISD::ADD:
13727         case ISD::SUB:
13728         case ISD::AND:
13729         case ISD::OR:
13730         case ISD::XOR: {
13731           NeedTruncation = true;
13732           ArithOp = Arith;
13733         }
13734       }
13735   }
13736
13737   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13738   // which may be the result of a CAST.  We use the variable 'Op', which is the
13739   // non-casted variable when we check for possible users.
13740   switch (ArithOp.getOpcode()) {
13741   case ISD::ADD:
13742     // Due to an isel shortcoming, be conservative if this add is likely to be
13743     // selected as part of a load-modify-store instruction. When the root node
13744     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13745     // uses of other nodes in the match, such as the ADD in this case. This
13746     // leads to the ADD being left around and reselected, with the result being
13747     // two adds in the output.  Alas, even if none our users are stores, that
13748     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13749     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13750     // climbing the DAG back to the root, and it doesn't seem to be worth the
13751     // effort.
13752     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13753          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13754       if (UI->getOpcode() != ISD::CopyToReg &&
13755           UI->getOpcode() != ISD::SETCC &&
13756           UI->getOpcode() != ISD::STORE)
13757         goto default_case;
13758
13759     if (ConstantSDNode *C =
13760         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13761       // An add of one will be selected as an INC.
13762       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13763         Opcode = X86ISD::INC;
13764         NumOperands = 1;
13765         break;
13766       }
13767
13768       // An add of negative one (subtract of one) will be selected as a DEC.
13769       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13770         Opcode = X86ISD::DEC;
13771         NumOperands = 1;
13772         break;
13773       }
13774     }
13775
13776     // Otherwise use a regular EFLAGS-setting add.
13777     Opcode = X86ISD::ADD;
13778     NumOperands = 2;
13779     break;
13780   case ISD::SHL:
13781   case ISD::SRL:
13782     // If we have a constant logical shift that's only used in a comparison
13783     // against zero turn it into an equivalent AND. This allows turning it into
13784     // a TEST instruction later.
13785     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13786         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13787       EVT VT = Op.getValueType();
13788       unsigned BitWidth = VT.getSizeInBits();
13789       unsigned ShAmt = Op->getConstantOperandVal(1);
13790       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13791         break;
13792       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13793                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13794                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13795       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13796         break;
13797       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13798                                 DAG.getConstant(Mask, dl, VT));
13799       DAG.ReplaceAllUsesWith(Op, New);
13800       Op = New;
13801     }
13802     break;
13803
13804   case ISD::AND:
13805     // If the primary and result isn't used, don't bother using X86ISD::AND,
13806     // because a TEST instruction will be better.
13807     if (!hasNonFlagsUse(Op))
13808       break;
13809     // FALL THROUGH
13810   case ISD::SUB:
13811   case ISD::OR:
13812   case ISD::XOR:
13813     // Due to the ISEL shortcoming noted above, be conservative if this op is
13814     // likely to be selected as part of a load-modify-store instruction.
13815     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13816            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13817       if (UI->getOpcode() == ISD::STORE)
13818         goto default_case;
13819
13820     // Otherwise use a regular EFLAGS-setting instruction.
13821     switch (ArithOp.getOpcode()) {
13822     default: llvm_unreachable("unexpected operator!");
13823     case ISD::SUB: Opcode = X86ISD::SUB; break;
13824     case ISD::XOR: Opcode = X86ISD::XOR; break;
13825     case ISD::AND: Opcode = X86ISD::AND; break;
13826     case ISD::OR: {
13827       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13828         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13829         if (EFLAGS.getNode())
13830           return EFLAGS;
13831       }
13832       Opcode = X86ISD::OR;
13833       break;
13834     }
13835     }
13836
13837     NumOperands = 2;
13838     break;
13839   case X86ISD::ADD:
13840   case X86ISD::SUB:
13841   case X86ISD::INC:
13842   case X86ISD::DEC:
13843   case X86ISD::OR:
13844   case X86ISD::XOR:
13845   case X86ISD::AND:
13846     return SDValue(Op.getNode(), 1);
13847   default:
13848   default_case:
13849     break;
13850   }
13851
13852   // If we found that truncation is beneficial, perform the truncation and
13853   // update 'Op'.
13854   if (NeedTruncation) {
13855     EVT VT = Op.getValueType();
13856     SDValue WideVal = Op->getOperand(0);
13857     EVT WideVT = WideVal.getValueType();
13858     unsigned ConvertedOp = 0;
13859     // Use a target machine opcode to prevent further DAGCombine
13860     // optimizations that may separate the arithmetic operations
13861     // from the setcc node.
13862     switch (WideVal.getOpcode()) {
13863       default: break;
13864       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13865       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13866       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13867       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13868       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13869     }
13870
13871     if (ConvertedOp) {
13872       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13873       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13874         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13875         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13876         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13877       }
13878     }
13879   }
13880
13881   if (Opcode == 0)
13882     // Emit a CMP with 0, which is the TEST pattern.
13883     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13884                        DAG.getConstant(0, dl, Op.getValueType()));
13885
13886   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13887   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13888
13889   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13890   DAG.ReplaceAllUsesWith(Op, New);
13891   return SDValue(New.getNode(), 1);
13892 }
13893
13894 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13895 /// equivalent.
13896 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13897                                    SDLoc dl, SelectionDAG &DAG) const {
13898   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13899     if (C->getAPIntValue() == 0)
13900       return EmitTest(Op0, X86CC, dl, DAG);
13901
13902      assert(Op0.getValueType() != MVT::i1 &&
13903             "Unexpected comparison operation for MVT::i1 operands");
13904   }
13905
13906   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13907        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13908     // Do the comparison at i32 if it's smaller, besides the Atom case.
13909     // This avoids subregister aliasing issues. Keep the smaller reference
13910     // if we're optimizing for size, however, as that'll allow better folding
13911     // of memory operations.
13912     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13913         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13914         !Subtarget->isAtom()) {
13915       unsigned ExtendOp =
13916           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13917       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13918       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13919     }
13920     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13921     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13922     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13923                               Op0, Op1);
13924     return SDValue(Sub.getNode(), 1);
13925   }
13926   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13927 }
13928
13929 /// Convert a comparison if required by the subtarget.
13930 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13931                                                  SelectionDAG &DAG) const {
13932   // If the subtarget does not support the FUCOMI instruction, floating-point
13933   // comparisons have to be converted.
13934   if (Subtarget->hasCMov() ||
13935       Cmp.getOpcode() != X86ISD::CMP ||
13936       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13937       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13938     return Cmp;
13939
13940   // The instruction selector will select an FUCOM instruction instead of
13941   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13942   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13943   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13944   SDLoc dl(Cmp);
13945   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13946   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13947   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13948                             DAG.getConstant(8, dl, MVT::i8));
13949   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13950   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13951 }
13952
13953 /// The minimum architected relative accuracy is 2^-12. We need one
13954 /// Newton-Raphson step to have a good float result (24 bits of precision).
13955 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13956                                             DAGCombinerInfo &DCI,
13957                                             unsigned &RefinementSteps,
13958                                             bool &UseOneConstNR) const {
13959   EVT VT = Op.getValueType();
13960   const char *RecipOp;
13961
13962   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13963   // TODO: Add support for AVX512 (v16f32).
13964   // It is likely not profitable to do this for f64 because a double-precision
13965   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13966   // instructions: convert to single, rsqrtss, convert back to double, refine
13967   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13968   // along with FMA, this could be a throughput win.
13969   if (VT == MVT::f32 && Subtarget->hasSSE1())
13970     RecipOp = "sqrtf";
13971   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13972            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13973     RecipOp = "vec-sqrtf";
13974   else
13975     return SDValue();
13976
13977   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13978   if (!Recips.isEnabled(RecipOp))
13979     return SDValue();
13980
13981   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13982   UseOneConstNR = false;
13983   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13984 }
13985
13986 /// The minimum architected relative accuracy is 2^-12. We need one
13987 /// Newton-Raphson step to have a good float result (24 bits of precision).
13988 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13989                                             DAGCombinerInfo &DCI,
13990                                             unsigned &RefinementSteps) const {
13991   EVT VT = Op.getValueType();
13992   const char *RecipOp;
13993
13994   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13995   // TODO: Add support for AVX512 (v16f32).
13996   // It is likely not profitable to do this for f64 because a double-precision
13997   // reciprocal estimate with refinement on x86 prior to FMA requires
13998   // 15 instructions: convert to single, rcpss, convert back to double, refine
13999   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14000   // along with FMA, this could be a throughput win.
14001   if (VT == MVT::f32 && Subtarget->hasSSE1())
14002     RecipOp = "divf";
14003   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14004            (VT == MVT::v8f32 && Subtarget->hasAVX()))
14005     RecipOp = "vec-divf";
14006   else
14007     return SDValue();
14008
14009   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14010   if (!Recips.isEnabled(RecipOp))
14011     return SDValue();
14012
14013   RefinementSteps = Recips.getRefinementSteps(RecipOp);
14014   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14015 }
14016
14017 /// If we have at least two divisions that use the same divisor, convert to
14018 /// multplication by a reciprocal. This may need to be adjusted for a given
14019 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14020 /// This is because we still need one division to calculate the reciprocal and
14021 /// then we need two multiplies by that reciprocal as replacements for the
14022 /// original divisions.
14023 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14024   return 2;
14025 }
14026
14027 static bool isAllOnes(SDValue V) {
14028   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14029   return C && C->isAllOnesValue();
14030 }
14031
14032 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14033 /// if it's possible.
14034 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14035                                      SDLoc dl, SelectionDAG &DAG) const {
14036   SDValue Op0 = And.getOperand(0);
14037   SDValue Op1 = And.getOperand(1);
14038   if (Op0.getOpcode() == ISD::TRUNCATE)
14039     Op0 = Op0.getOperand(0);
14040   if (Op1.getOpcode() == ISD::TRUNCATE)
14041     Op1 = Op1.getOperand(0);
14042
14043   SDValue LHS, RHS;
14044   if (Op1.getOpcode() == ISD::SHL)
14045     std::swap(Op0, Op1);
14046   if (Op0.getOpcode() == ISD::SHL) {
14047     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
14048       if (And00C->getZExtValue() == 1) {
14049         // If we looked past a truncate, check that it's only truncating away
14050         // known zeros.
14051         unsigned BitWidth = Op0.getValueSizeInBits();
14052         unsigned AndBitWidth = And.getValueSizeInBits();
14053         if (BitWidth > AndBitWidth) {
14054           APInt Zeros, Ones;
14055           DAG.computeKnownBits(Op0, Zeros, Ones);
14056           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14057             return SDValue();
14058         }
14059         LHS = Op1;
14060         RHS = Op0.getOperand(1);
14061       }
14062   } else if (Op1.getOpcode() == ISD::Constant) {
14063     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14064     uint64_t AndRHSVal = AndRHS->getZExtValue();
14065     SDValue AndLHS = Op0;
14066
14067     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14068       LHS = AndLHS.getOperand(0);
14069       RHS = AndLHS.getOperand(1);
14070     }
14071
14072     // Use BT if the immediate can't be encoded in a TEST instruction.
14073     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14074       LHS = AndLHS;
14075       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14076     }
14077   }
14078
14079   if (LHS.getNode()) {
14080     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
14081     // instruction.  Since the shift amount is in-range-or-undefined, we know
14082     // that doing a bittest on the i32 value is ok.  We extend to i32 because
14083     // the encoding for the i16 version is larger than the i32 version.
14084     // Also promote i16 to i32 for performance / code size reason.
14085     if (LHS.getValueType() == MVT::i8 ||
14086         LHS.getValueType() == MVT::i16)
14087       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14088
14089     // If the operand types disagree, extend the shift amount to match.  Since
14090     // BT ignores high bits (like shifts) we can use anyextend.
14091     if (LHS.getValueType() != RHS.getValueType())
14092       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14093
14094     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14095     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14096     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14097                        DAG.getConstant(Cond, dl, MVT::i8), BT);
14098   }
14099
14100   return SDValue();
14101 }
14102
14103 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14104 /// mask CMPs.
14105 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14106                               SDValue &Op1) {
14107   unsigned SSECC;
14108   bool Swap = false;
14109
14110   // SSE Condition code mapping:
14111   //  0 - EQ
14112   //  1 - LT
14113   //  2 - LE
14114   //  3 - UNORD
14115   //  4 - NEQ
14116   //  5 - NLT
14117   //  6 - NLE
14118   //  7 - ORD
14119   switch (SetCCOpcode) {
14120   default: llvm_unreachable("Unexpected SETCC condition");
14121   case ISD::SETOEQ:
14122   case ISD::SETEQ:  SSECC = 0; break;
14123   case ISD::SETOGT:
14124   case ISD::SETGT:  Swap = true; // Fallthrough
14125   case ISD::SETLT:
14126   case ISD::SETOLT: SSECC = 1; break;
14127   case ISD::SETOGE:
14128   case ISD::SETGE:  Swap = true; // Fallthrough
14129   case ISD::SETLE:
14130   case ISD::SETOLE: SSECC = 2; break;
14131   case ISD::SETUO:  SSECC = 3; break;
14132   case ISD::SETUNE:
14133   case ISD::SETNE:  SSECC = 4; break;
14134   case ISD::SETULE: Swap = true; // Fallthrough
14135   case ISD::SETUGE: SSECC = 5; break;
14136   case ISD::SETULT: Swap = true; // Fallthrough
14137   case ISD::SETUGT: SSECC = 6; break;
14138   case ISD::SETO:   SSECC = 7; break;
14139   case ISD::SETUEQ:
14140   case ISD::SETONE: SSECC = 8; break;
14141   }
14142   if (Swap)
14143     std::swap(Op0, Op1);
14144
14145   return SSECC;
14146 }
14147
14148 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14149 // ones, and then concatenate the result back.
14150 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14151   MVT VT = Op.getSimpleValueType();
14152
14153   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14154          "Unsupported value type for operation");
14155
14156   unsigned NumElems = VT.getVectorNumElements();
14157   SDLoc dl(Op);
14158   SDValue CC = Op.getOperand(2);
14159
14160   // Extract the LHS vectors
14161   SDValue LHS = Op.getOperand(0);
14162   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14163   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14164
14165   // Extract the RHS vectors
14166   SDValue RHS = Op.getOperand(1);
14167   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14168   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14169
14170   // Issue the operation on the smaller types and concatenate the result back
14171   MVT EltVT = VT.getVectorElementType();
14172   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14173   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14174                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14175                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14176 }
14177
14178 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14179   SDValue Op0 = Op.getOperand(0);
14180   SDValue Op1 = Op.getOperand(1);
14181   SDValue CC = Op.getOperand(2);
14182   MVT VT = Op.getSimpleValueType();
14183   SDLoc dl(Op);
14184
14185   assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14186          "Unexpected type for boolean compare operation");
14187   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14188   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14189                                DAG.getConstant(-1, dl, VT));
14190   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14191                                DAG.getConstant(-1, dl, VT));
14192   switch (SetCCOpcode) {
14193   default: llvm_unreachable("Unexpected SETCC condition");
14194   case ISD::SETEQ:
14195     // (x == y) -> ~(x ^ y)
14196     return DAG.getNode(ISD::XOR, dl, VT,
14197                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14198                        DAG.getConstant(-1, dl, VT));
14199   case ISD::SETNE:
14200     // (x != y) -> (x ^ y)
14201     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14202   case ISD::SETUGT:
14203   case ISD::SETGT:
14204     // (x > y) -> (x & ~y)
14205     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14206   case ISD::SETULT:
14207   case ISD::SETLT:
14208     // (x < y) -> (~x & y)
14209     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14210   case ISD::SETULE:
14211   case ISD::SETLE:
14212     // (x <= y) -> (~x | y)
14213     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14214   case ISD::SETUGE:
14215   case ISD::SETGE:
14216     // (x >=y) -> (x | ~y)
14217     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14218   }
14219 }
14220
14221 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14222                                      const X86Subtarget *Subtarget) {
14223   SDValue Op0 = Op.getOperand(0);
14224   SDValue Op1 = Op.getOperand(1);
14225   SDValue CC = Op.getOperand(2);
14226   MVT VT = Op.getSimpleValueType();
14227   SDLoc dl(Op);
14228
14229   assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14230          Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14231          "Cannot set masked compare for this operation");
14232
14233   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14234   unsigned  Opc = 0;
14235   bool Unsigned = false;
14236   bool Swap = false;
14237   unsigned SSECC;
14238   switch (SetCCOpcode) {
14239   default: llvm_unreachable("Unexpected SETCC condition");
14240   case ISD::SETNE:  SSECC = 4; break;
14241   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
14242   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14243   case ISD::SETLT:  Swap = true; //fall-through
14244   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
14245   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14246   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14247   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
14248   case ISD::SETULE: Unsigned = true; //fall-through
14249   case ISD::SETLE:  SSECC = 2; break;
14250   }
14251
14252   if (Swap)
14253     std::swap(Op0, Op1);
14254   if (Opc)
14255     return DAG.getNode(Opc, dl, VT, Op0, Op1);
14256   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14257   return DAG.getNode(Opc, dl, VT, Op0, Op1,
14258                      DAG.getConstant(SSECC, dl, MVT::i8));
14259 }
14260
14261 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14262 /// operand \p Op1.  If non-trivial (for example because it's not constant)
14263 /// return an empty value.
14264 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14265 {
14266   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14267   if (!BV)
14268     return SDValue();
14269
14270   MVT VT = Op1.getSimpleValueType();
14271   MVT EVT = VT.getVectorElementType();
14272   unsigned n = VT.getVectorNumElements();
14273   SmallVector<SDValue, 8> ULTOp1;
14274
14275   for (unsigned i = 0; i < n; ++i) {
14276     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14277     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14278       return SDValue();
14279
14280     // Avoid underflow.
14281     APInt Val = Elt->getAPIntValue();
14282     if (Val == 0)
14283       return SDValue();
14284
14285     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14286   }
14287
14288   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14289 }
14290
14291 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14292                            SelectionDAG &DAG) {
14293   SDValue Op0 = Op.getOperand(0);
14294   SDValue Op1 = Op.getOperand(1);
14295   SDValue CC = Op.getOperand(2);
14296   MVT VT = Op.getSimpleValueType();
14297   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14298   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14299   SDLoc dl(Op);
14300
14301   if (isFP) {
14302 #ifndef NDEBUG
14303     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14304     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14305 #endif
14306
14307     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14308     unsigned Opc = X86ISD::CMPP;
14309     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14310       assert(VT.getVectorNumElements() <= 16);
14311       Opc = X86ISD::CMPM;
14312     }
14313     // In the two special cases we can't handle, emit two comparisons.
14314     if (SSECC == 8) {
14315       unsigned CC0, CC1;
14316       unsigned CombineOpc;
14317       if (SetCCOpcode == ISD::SETUEQ) {
14318         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14319       } else {
14320         assert(SetCCOpcode == ISD::SETONE);
14321         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14322       }
14323
14324       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14325                                  DAG.getConstant(CC0, dl, MVT::i8));
14326       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14327                                  DAG.getConstant(CC1, dl, MVT::i8));
14328       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14329     }
14330     // Handle all other FP comparisons here.
14331     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14332                        DAG.getConstant(SSECC, dl, MVT::i8));
14333   }
14334
14335   MVT VTOp0 = Op0.getSimpleValueType();
14336   assert(VTOp0 == Op1.getSimpleValueType() &&
14337          "Expected operands with same type!");
14338   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14339          "Invalid number of packed elements for source and destination!");
14340
14341   if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14342     // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14343     // legalizer to a wider vector type.  In the case of 'vsetcc' nodes, the
14344     // legalizer firstly checks if the first operand in input to the setcc has
14345     // a legal type. If so, then it promotes the return type to that same type.
14346     // Otherwise, the return type is promoted to the 'next legal type' which,
14347     // for a vector of MVT::i1 is always a 128-bit integer vector type.
14348     //
14349     // We reach this code only if the following two conditions are met:
14350     // 1. Both return type and operand type have been promoted to wider types
14351     //    by the type legalizer.
14352     // 2. The original operand type has been promoted to a 256-bit vector.
14353     //
14354     // Note that condition 2. only applies for AVX targets.
14355     SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14356     return DAG.getZExtOrTrunc(NewOp, dl, VT);
14357   }
14358
14359   // The non-AVX512 code below works under the assumption that source and
14360   // destination types are the same.
14361   assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14362          "Value types for source and destination must be the same!");
14363
14364   // Break 256-bit integer vector compare into smaller ones.
14365   if (VT.is256BitVector() && !Subtarget->hasInt256())
14366     return Lower256IntVSETCC(Op, DAG);
14367
14368   MVT OpVT = Op1.getSimpleValueType();
14369   if (OpVT.getVectorElementType() == MVT::i1)
14370     return LowerBoolVSETCC_AVX512(Op, DAG);
14371
14372   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14373   if (Subtarget->hasAVX512()) {
14374     if (Op1.getSimpleValueType().is512BitVector() ||
14375         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14376         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14377       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14378
14379     // In AVX-512 architecture setcc returns mask with i1 elements,
14380     // But there is no compare instruction for i8 and i16 elements in KNL.
14381     // We are not talking about 512-bit operands in this case, these
14382     // types are illegal.
14383     if (MaskResult &&
14384         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14385          OpVT.getVectorElementType().getSizeInBits() >= 8))
14386       return DAG.getNode(ISD::TRUNCATE, dl, VT,
14387                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14388   }
14389
14390   // Lower using XOP integer comparisons.
14391   if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14392        VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14393     // Translate compare code to XOP PCOM compare mode.
14394     unsigned CmpMode = 0;
14395     switch (SetCCOpcode) {
14396     default: llvm_unreachable("Unexpected SETCC condition");
14397     case ISD::SETULT:
14398     case ISD::SETLT: CmpMode = 0x00; break;
14399     case ISD::SETULE:
14400     case ISD::SETLE: CmpMode = 0x01; break;
14401     case ISD::SETUGT:
14402     case ISD::SETGT: CmpMode = 0x02; break;
14403     case ISD::SETUGE:
14404     case ISD::SETGE: CmpMode = 0x03; break;
14405     case ISD::SETEQ: CmpMode = 0x04; break;
14406     case ISD::SETNE: CmpMode = 0x05; break;
14407     }
14408
14409     // Are we comparing unsigned or signed integers?
14410     unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14411       ? X86ISD::VPCOMU : X86ISD::VPCOM;
14412
14413     return DAG.getNode(Opc, dl, VT, Op0, Op1,
14414                        DAG.getConstant(CmpMode, dl, MVT::i8));
14415   }
14416
14417   // We are handling one of the integer comparisons here.  Since SSE only has
14418   // GT and EQ comparisons for integer, swapping operands and multiple
14419   // operations may be required for some comparisons.
14420   unsigned Opc;
14421   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14422   bool Subus = false;
14423
14424   switch (SetCCOpcode) {
14425   default: llvm_unreachable("Unexpected SETCC condition");
14426   case ISD::SETNE:  Invert = true;
14427   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
14428   case ISD::SETLT:  Swap = true;
14429   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14430   case ISD::SETGE:  Swap = true;
14431   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14432                     Invert = true; break;
14433   case ISD::SETULT: Swap = true;
14434   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14435                     FlipSigns = true; break;
14436   case ISD::SETUGE: Swap = true;
14437   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14438                     FlipSigns = true; Invert = true; break;
14439   }
14440
14441   // Special case: Use min/max operations for SETULE/SETUGE
14442   MVT VET = VT.getVectorElementType();
14443   bool hasMinMax =
14444        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14445     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14446
14447   if (hasMinMax) {
14448     switch (SetCCOpcode) {
14449     default: break;
14450     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14451     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14452     }
14453
14454     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14455   }
14456
14457   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14458   if (!MinMax && hasSubus) {
14459     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14460     // Op0 u<= Op1:
14461     //   t = psubus Op0, Op1
14462     //   pcmpeq t, <0..0>
14463     switch (SetCCOpcode) {
14464     default: break;
14465     case ISD::SETULT: {
14466       // If the comparison is against a constant we can turn this into a
14467       // setule.  With psubus, setule does not require a swap.  This is
14468       // beneficial because the constant in the register is no longer
14469       // destructed as the destination so it can be hoisted out of a loop.
14470       // Only do this pre-AVX since vpcmp* is no longer destructive.
14471       if (Subtarget->hasAVX())
14472         break;
14473       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14474       if (ULEOp1.getNode()) {
14475         Op1 = ULEOp1;
14476         Subus = true; Invert = false; Swap = false;
14477       }
14478       break;
14479     }
14480     // Psubus is better than flip-sign because it requires no inversion.
14481     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14482     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14483     }
14484
14485     if (Subus) {
14486       Opc = X86ISD::SUBUS;
14487       FlipSigns = false;
14488     }
14489   }
14490
14491   if (Swap)
14492     std::swap(Op0, Op1);
14493
14494   // Check that the operation in question is available (most are plain SSE2,
14495   // but PCMPGTQ and PCMPEQQ have different requirements).
14496   if (VT == MVT::v2i64) {
14497     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14498       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14499
14500       // First cast everything to the right type.
14501       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14502       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14503
14504       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14505       // bits of the inputs before performing those operations. The lower
14506       // compare is always unsigned.
14507       SDValue SB;
14508       if (FlipSigns) {
14509         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14510       } else {
14511         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14512         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14513         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14514                          Sign, Zero, Sign, Zero);
14515       }
14516       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14517       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14518
14519       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14520       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14521       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14522
14523       // Create masks for only the low parts/high parts of the 64 bit integers.
14524       static const int MaskHi[] = { 1, 1, 3, 3 };
14525       static const int MaskLo[] = { 0, 0, 2, 2 };
14526       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14527       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14528       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14529
14530       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14531       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14532
14533       if (Invert)
14534         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14535
14536       return DAG.getBitcast(VT, Result);
14537     }
14538
14539     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14540       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14541       // pcmpeqd + pshufd + pand.
14542       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14543
14544       // First cast everything to the right type.
14545       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14546       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14547
14548       // Do the compare.
14549       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14550
14551       // Make sure the lower and upper halves are both all-ones.
14552       static const int Mask[] = { 1, 0, 3, 2 };
14553       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14554       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14555
14556       if (Invert)
14557         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14558
14559       return DAG.getBitcast(VT, Result);
14560     }
14561   }
14562
14563   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14564   // bits of the inputs before performing those operations.
14565   if (FlipSigns) {
14566     MVT EltVT = VT.getVectorElementType();
14567     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14568                                  VT);
14569     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14570     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14571   }
14572
14573   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14574
14575   // If the logical-not of the result is required, perform that now.
14576   if (Invert)
14577     Result = DAG.getNOT(dl, Result, VT);
14578
14579   if (MinMax)
14580     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14581
14582   if (Subus)
14583     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14584                          getZeroVector(VT, Subtarget, DAG, dl));
14585
14586   return Result;
14587 }
14588
14589 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14590
14591   MVT VT = Op.getSimpleValueType();
14592
14593   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14594
14595   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14596          && "SetCC type must be 8-bit or 1-bit integer");
14597   SDValue Op0 = Op.getOperand(0);
14598   SDValue Op1 = Op.getOperand(1);
14599   SDLoc dl(Op);
14600   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14601
14602   // Optimize to BT if possible.
14603   // Lower (X & (1 << N)) == 0 to BT(X, N).
14604   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14605   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14606   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14607       Op1.getOpcode() == ISD::Constant &&
14608       cast<ConstantSDNode>(Op1)->isNullValue() &&
14609       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14610     if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14611       if (VT == MVT::i1)
14612         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14613       return NewSetCC;
14614     }
14615   }
14616
14617   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14618   // these.
14619   if (Op1.getOpcode() == ISD::Constant &&
14620       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14621        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14622       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14623
14624     // If the input is a setcc, then reuse the input setcc or use a new one with
14625     // the inverted condition.
14626     if (Op0.getOpcode() == X86ISD::SETCC) {
14627       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14628       bool Invert = (CC == ISD::SETNE) ^
14629         cast<ConstantSDNode>(Op1)->isNullValue();
14630       if (!Invert)
14631         return Op0;
14632
14633       CCode = X86::GetOppositeBranchCondition(CCode);
14634       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14635                                   DAG.getConstant(CCode, dl, MVT::i8),
14636                                   Op0.getOperand(1));
14637       if (VT == MVT::i1)
14638         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14639       return SetCC;
14640     }
14641   }
14642   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14643       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14644       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14645
14646     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14647     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14648   }
14649
14650   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14651   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14652   if (X86CC == X86::COND_INVALID)
14653     return SDValue();
14654
14655   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14656   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14657   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14658                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14659   if (VT == MVT::i1)
14660     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14661   return SetCC;
14662 }
14663
14664 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14665   SDValue LHS = Op.getOperand(0);
14666   SDValue RHS = Op.getOperand(1);
14667   SDValue Carry = Op.getOperand(2);
14668   SDValue Cond = Op.getOperand(3);
14669   SDLoc DL(Op);
14670
14671   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14672   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14673
14674   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14675   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14676   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14677   return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14678                      DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14679 }
14680
14681 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14682 static bool isX86LogicalCmp(SDValue Op) {
14683   unsigned Opc = Op.getNode()->getOpcode();
14684   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14685       Opc == X86ISD::SAHF)
14686     return true;
14687   if (Op.getResNo() == 1 &&
14688       (Opc == X86ISD::ADD ||
14689        Opc == X86ISD::SUB ||
14690        Opc == X86ISD::ADC ||
14691        Opc == X86ISD::SBB ||
14692        Opc == X86ISD::SMUL ||
14693        Opc == X86ISD::UMUL ||
14694        Opc == X86ISD::INC ||
14695        Opc == X86ISD::DEC ||
14696        Opc == X86ISD::OR ||
14697        Opc == X86ISD::XOR ||
14698        Opc == X86ISD::AND))
14699     return true;
14700
14701   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14702     return true;
14703
14704   return false;
14705 }
14706
14707 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14708   if (V.getOpcode() != ISD::TRUNCATE)
14709     return false;
14710
14711   SDValue VOp0 = V.getOperand(0);
14712   unsigned InBits = VOp0.getValueSizeInBits();
14713   unsigned Bits = V.getValueSizeInBits();
14714   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14715 }
14716
14717 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14718   bool addTest = true;
14719   SDValue Cond  = Op.getOperand(0);
14720   SDValue Op1 = Op.getOperand(1);
14721   SDValue Op2 = Op.getOperand(2);
14722   SDLoc DL(Op);
14723   MVT VT = Op1.getSimpleValueType();
14724   SDValue CC;
14725
14726   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14727   // are available or VBLENDV if AVX is available.
14728   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14729   if (Cond.getOpcode() == ISD::SETCC &&
14730       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14731        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14732       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14733     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14734     int SSECC = translateX86FSETCC(
14735         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14736
14737     if (SSECC != 8) {
14738       if (Subtarget->hasAVX512()) {
14739         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14740                                   DAG.getConstant(SSECC, DL, MVT::i8));
14741         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14742       }
14743
14744       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14745                                 DAG.getConstant(SSECC, DL, MVT::i8));
14746
14747       // If we have AVX, we can use a variable vector select (VBLENDV) instead
14748       // of 3 logic instructions for size savings and potentially speed.
14749       // Unfortunately, there is no scalar form of VBLENDV.
14750
14751       // If either operand is a constant, don't try this. We can expect to
14752       // optimize away at least one of the logic instructions later in that
14753       // case, so that sequence would be faster than a variable blend.
14754
14755       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14756       // uses XMM0 as the selection register. That may need just as many
14757       // instructions as the AND/ANDN/OR sequence due to register moves, so
14758       // don't bother.
14759
14760       if (Subtarget->hasAVX() &&
14761           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14762
14763         // Convert to vectors, do a VSELECT, and convert back to scalar.
14764         // All of the conversions should be optimized away.
14765
14766         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14767         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14768         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14769         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14770
14771         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14772         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14773
14774         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14775
14776         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14777                            VSel, DAG.getIntPtrConstant(0, DL));
14778       }
14779       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14780       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14781       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14782     }
14783   }
14784
14785   if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
14786     SDValue Op1Scalar;
14787     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14788       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14789     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14790       Op1Scalar = Op1.getOperand(0);
14791     SDValue Op2Scalar;
14792     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14793       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14794     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14795       Op2Scalar = Op2.getOperand(0);
14796     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14797       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14798                                       Op1Scalar.getValueType(),
14799                                       Cond, Op1Scalar, Op2Scalar);
14800       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14801         return DAG.getBitcast(VT, newSelect);
14802       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14803       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14804                          DAG.getIntPtrConstant(0, DL));
14805     }
14806   }
14807
14808   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14809     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14810     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14811                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14812     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14813                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14814     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14815                                     Cond, Op1, Op2);
14816     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14817   }
14818
14819   if (Cond.getOpcode() == ISD::SETCC) {
14820     SDValue NewCond = LowerSETCC(Cond, DAG);
14821     if (NewCond.getNode())
14822       Cond = NewCond;
14823   }
14824
14825   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14826   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14827   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14828   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14829   if (Cond.getOpcode() == X86ISD::SETCC &&
14830       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14831       isZero(Cond.getOperand(1).getOperand(1))) {
14832     SDValue Cmp = Cond.getOperand(1);
14833
14834     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14835
14836     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14837         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14838       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14839
14840       SDValue CmpOp0 = Cmp.getOperand(0);
14841       // Apply further optimizations for special cases
14842       // (select (x != 0), -1, 0) -> neg & sbb
14843       // (select (x == 0), 0, -1) -> neg & sbb
14844       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14845         if (YC->isNullValue() &&
14846             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14847           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14848           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14849                                     DAG.getConstant(0, DL,
14850                                                     CmpOp0.getValueType()),
14851                                     CmpOp0);
14852           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14853                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14854                                     SDValue(Neg.getNode(), 1));
14855           return Res;
14856         }
14857
14858       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14859                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14860       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14861
14862       SDValue Res =   // Res = 0 or -1.
14863         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14864                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14865
14866       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14867         Res = DAG.getNOT(DL, Res, Res.getValueType());
14868
14869       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14870       if (!N2C || !N2C->isNullValue())
14871         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14872       return Res;
14873     }
14874   }
14875
14876   // Look past (and (setcc_carry (cmp ...)), 1).
14877   if (Cond.getOpcode() == ISD::AND &&
14878       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14879     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14880     if (C && C->getAPIntValue() == 1)
14881       Cond = Cond.getOperand(0);
14882   }
14883
14884   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14885   // setting operand in place of the X86ISD::SETCC.
14886   unsigned CondOpcode = Cond.getOpcode();
14887   if (CondOpcode == X86ISD::SETCC ||
14888       CondOpcode == X86ISD::SETCC_CARRY) {
14889     CC = Cond.getOperand(0);
14890
14891     SDValue Cmp = Cond.getOperand(1);
14892     unsigned Opc = Cmp.getOpcode();
14893     MVT VT = Op.getSimpleValueType();
14894
14895     bool IllegalFPCMov = false;
14896     if (VT.isFloatingPoint() && !VT.isVector() &&
14897         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14898       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14899
14900     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14901         Opc == X86ISD::BT) { // FIXME
14902       Cond = Cmp;
14903       addTest = false;
14904     }
14905   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14906              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14907              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14908               Cond.getOperand(0).getValueType() != MVT::i8)) {
14909     SDValue LHS = Cond.getOperand(0);
14910     SDValue RHS = Cond.getOperand(1);
14911     unsigned X86Opcode;
14912     unsigned X86Cond;
14913     SDVTList VTs;
14914     switch (CondOpcode) {
14915     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14916     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14917     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14918     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14919     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14920     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14921     default: llvm_unreachable("unexpected overflowing operator");
14922     }
14923     if (CondOpcode == ISD::UMULO)
14924       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14925                           MVT::i32);
14926     else
14927       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14928
14929     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14930
14931     if (CondOpcode == ISD::UMULO)
14932       Cond = X86Op.getValue(2);
14933     else
14934       Cond = X86Op.getValue(1);
14935
14936     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14937     addTest = false;
14938   }
14939
14940   if (addTest) {
14941     // Look past the truncate if the high bits are known zero.
14942     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14943       Cond = Cond.getOperand(0);
14944
14945     // We know the result of AND is compared against zero. Try to match
14946     // it to BT.
14947     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14948       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
14949         CC = NewSetCC.getOperand(0);
14950         Cond = NewSetCC.getOperand(1);
14951         addTest = false;
14952       }
14953     }
14954   }
14955
14956   if (addTest) {
14957     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14958     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14959   }
14960
14961   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14962   // a <  b ?  0 : -1 -> RES = setcc_carry
14963   // a >= b ? -1 :  0 -> RES = setcc_carry
14964   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14965   if (Cond.getOpcode() == X86ISD::SUB) {
14966     Cond = ConvertCmpIfNecessary(Cond, DAG);
14967     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14968
14969     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14970         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14971       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14972                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14973                                 Cond);
14974       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14975         return DAG.getNOT(DL, Res, Res.getValueType());
14976       return Res;
14977     }
14978   }
14979
14980   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14981   // widen the cmov and push the truncate through. This avoids introducing a new
14982   // branch during isel and doesn't add any extensions.
14983   if (Op.getValueType() == MVT::i8 &&
14984       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14985     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14986     if (T1.getValueType() == T2.getValueType() &&
14987         // Blacklist CopyFromReg to avoid partial register stalls.
14988         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14989       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14990       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14991       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14992     }
14993   }
14994
14995   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14996   // condition is true.
14997   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14998   SDValue Ops[] = { Op2, Op1, CC, Cond };
14999   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15000 }
15001
15002 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15003                                        const X86Subtarget *Subtarget,
15004                                        SelectionDAG &DAG) {
15005   MVT VT = Op->getSimpleValueType(0);
15006   SDValue In = Op->getOperand(0);
15007   MVT InVT = In.getSimpleValueType();
15008   MVT VTElt = VT.getVectorElementType();
15009   MVT InVTElt = InVT.getVectorElementType();
15010   SDLoc dl(Op);
15011
15012   // SKX processor
15013   if ((InVTElt == MVT::i1) &&
15014       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15015         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15016
15017        ((Subtarget->hasBWI() && VT.is512BitVector() &&
15018         VTElt.getSizeInBits() <= 16)) ||
15019
15020        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15021         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15022
15023        ((Subtarget->hasDQI() && VT.is512BitVector() &&
15024         VTElt.getSizeInBits() >= 32))))
15025     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15026
15027   unsigned int NumElts = VT.getVectorNumElements();
15028
15029   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15030     return SDValue();
15031
15032   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15033     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15034       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15035     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15036   }
15037
15038   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15039   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15040   SDValue NegOne =
15041    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15042                    ExtVT);
15043   SDValue Zero =
15044    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15045
15046   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15047   if (VT.is512BitVector())
15048     return V;
15049   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15050 }
15051
15052 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15053                                              const X86Subtarget *Subtarget,
15054                                              SelectionDAG &DAG) {
15055   SDValue In = Op->getOperand(0);
15056   MVT VT = Op->getSimpleValueType(0);
15057   MVT InVT = In.getSimpleValueType();
15058   assert(VT.getSizeInBits() == InVT.getSizeInBits());
15059
15060   MVT InSVT = InVT.getVectorElementType();
15061   assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15062
15063   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15064     return SDValue();
15065   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15066     return SDValue();
15067
15068   SDLoc dl(Op);
15069
15070   // SSE41 targets can use the pmovsx* instructions directly.
15071   if (Subtarget->hasSSE41())
15072     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15073
15074   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15075   SDValue Curr = In;
15076   MVT CurrVT = InVT;
15077
15078   // As SRAI is only available on i16/i32 types, we expand only up to i32
15079   // and handle i64 separately.
15080   while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15081     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15082     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15083     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15084     Curr = DAG.getBitcast(CurrVT, Curr);
15085   }
15086
15087   SDValue SignExt = Curr;
15088   if (CurrVT != InVT) {
15089     unsigned SignExtShift =
15090         CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15091     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15092                           DAG.getConstant(SignExtShift, dl, MVT::i8));
15093   }
15094
15095   if (CurrVT == VT)
15096     return SignExt;
15097
15098   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15099     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15100                                DAG.getConstant(31, dl, MVT::i8));
15101     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15102     return DAG.getBitcast(VT, Ext);
15103   }
15104
15105   return SDValue();
15106 }
15107
15108 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15109                                 SelectionDAG &DAG) {
15110   MVT VT = Op->getSimpleValueType(0);
15111   SDValue In = Op->getOperand(0);
15112   MVT InVT = In.getSimpleValueType();
15113   SDLoc dl(Op);
15114
15115   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15116     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15117
15118   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15119       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15120       (VT != MVT::v16i16 || InVT != MVT::v16i8))
15121     return SDValue();
15122
15123   if (Subtarget->hasInt256())
15124     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15125
15126   // Optimize vectors in AVX mode
15127   // Sign extend  v8i16 to v8i32 and
15128   //              v4i32 to v4i64
15129   //
15130   // Divide input vector into two parts
15131   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15132   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15133   // concat the vectors to original VT
15134
15135   unsigned NumElems = InVT.getVectorNumElements();
15136   SDValue Undef = DAG.getUNDEF(InVT);
15137
15138   SmallVector<int,8> ShufMask1(NumElems, -1);
15139   for (unsigned i = 0; i != NumElems/2; ++i)
15140     ShufMask1[i] = i;
15141
15142   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15143
15144   SmallVector<int,8> ShufMask2(NumElems, -1);
15145   for (unsigned i = 0; i != NumElems/2; ++i)
15146     ShufMask2[i] = i + NumElems/2;
15147
15148   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15149
15150   MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15151                                 VT.getVectorNumElements()/2);
15152
15153   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15154   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15155
15156   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15157 }
15158
15159 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15160 // may emit an illegal shuffle but the expansion is still better than scalar
15161 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15162 // we'll emit a shuffle and a arithmetic shift.
15163 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15164 // TODO: It is possible to support ZExt by zeroing the undef values during
15165 // the shuffle phase or after the shuffle.
15166 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15167                                  SelectionDAG &DAG) {
15168   MVT RegVT = Op.getSimpleValueType();
15169   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15170   assert(RegVT.isInteger() &&
15171          "We only custom lower integer vector sext loads.");
15172
15173   // Nothing useful we can do without SSE2 shuffles.
15174   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15175
15176   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15177   SDLoc dl(Ld);
15178   EVT MemVT = Ld->getMemoryVT();
15179   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15180   unsigned RegSz = RegVT.getSizeInBits();
15181
15182   ISD::LoadExtType Ext = Ld->getExtensionType();
15183
15184   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15185          && "Only anyext and sext are currently implemented.");
15186   assert(MemVT != RegVT && "Cannot extend to the same type");
15187   assert(MemVT.isVector() && "Must load a vector from memory");
15188
15189   unsigned NumElems = RegVT.getVectorNumElements();
15190   unsigned MemSz = MemVT.getSizeInBits();
15191   assert(RegSz > MemSz && "Register size must be greater than the mem size");
15192
15193   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15194     // The only way in which we have a legal 256-bit vector result but not the
15195     // integer 256-bit operations needed to directly lower a sextload is if we
15196     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15197     // a 128-bit vector and a normal sign_extend to 256-bits that should get
15198     // correctly legalized. We do this late to allow the canonical form of
15199     // sextload to persist throughout the rest of the DAG combiner -- it wants
15200     // to fold together any extensions it can, and so will fuse a sign_extend
15201     // of an sextload into a sextload targeting a wider value.
15202     SDValue Load;
15203     if (MemSz == 128) {
15204       // Just switch this to a normal load.
15205       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15206                                        "it must be a legal 128-bit vector "
15207                                        "type!");
15208       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15209                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15210                   Ld->isInvariant(), Ld->getAlignment());
15211     } else {
15212       assert(MemSz < 128 &&
15213              "Can't extend a type wider than 128 bits to a 256 bit vector!");
15214       // Do an sext load to a 128-bit vector type. We want to use the same
15215       // number of elements, but elements half as wide. This will end up being
15216       // recursively lowered by this routine, but will succeed as we definitely
15217       // have all the necessary features if we're using AVX1.
15218       EVT HalfEltVT =
15219           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15220       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15221       Load =
15222           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15223                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15224                          Ld->isNonTemporal(), Ld->isInvariant(),
15225                          Ld->getAlignment());
15226     }
15227
15228     // Replace chain users with the new chain.
15229     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15230     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15231
15232     // Finally, do a normal sign-extend to the desired register.
15233     return DAG.getSExtOrTrunc(Load, dl, RegVT);
15234   }
15235
15236   // All sizes must be a power of two.
15237   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15238          "Non-power-of-two elements are not custom lowered!");
15239
15240   // Attempt to load the original value using scalar loads.
15241   // Find the largest scalar type that divides the total loaded size.
15242   MVT SclrLoadTy = MVT::i8;
15243   for (MVT Tp : MVT::integer_valuetypes()) {
15244     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15245       SclrLoadTy = Tp;
15246     }
15247   }
15248
15249   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15250   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15251       (64 <= MemSz))
15252     SclrLoadTy = MVT::f64;
15253
15254   // Calculate the number of scalar loads that we need to perform
15255   // in order to load our vector from memory.
15256   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15257
15258   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15259          "Can only lower sext loads with a single scalar load!");
15260
15261   unsigned loadRegZize = RegSz;
15262   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15263     loadRegZize = 128;
15264
15265   // Represent our vector as a sequence of elements which are the
15266   // largest scalar that we can load.
15267   EVT LoadUnitVecVT = EVT::getVectorVT(
15268       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15269
15270   // Represent the data using the same element type that is stored in
15271   // memory. In practice, we ''widen'' MemVT.
15272   EVT WideVecVT =
15273       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15274                        loadRegZize / MemVT.getScalarSizeInBits());
15275
15276   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15277          "Invalid vector type");
15278
15279   // We can't shuffle using an illegal type.
15280   assert(TLI.isTypeLegal(WideVecVT) &&
15281          "We only lower types that form legal widened vector types");
15282
15283   SmallVector<SDValue, 8> Chains;
15284   SDValue Ptr = Ld->getBasePtr();
15285   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15286                                       TLI.getPointerTy(DAG.getDataLayout()));
15287   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15288
15289   for (unsigned i = 0; i < NumLoads; ++i) {
15290     // Perform a single load.
15291     SDValue ScalarLoad =
15292         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15293                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15294                     Ld->getAlignment());
15295     Chains.push_back(ScalarLoad.getValue(1));
15296     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15297     // another round of DAGCombining.
15298     if (i == 0)
15299       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15300     else
15301       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15302                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
15303
15304     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15305   }
15306
15307   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15308
15309   // Bitcast the loaded value to a vector of the original element type, in
15310   // the size of the target vector type.
15311   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15312   unsigned SizeRatio = RegSz / MemSz;
15313
15314   if (Ext == ISD::SEXTLOAD) {
15315     // If we have SSE4.1, we can directly emit a VSEXT node.
15316     if (Subtarget->hasSSE41()) {
15317       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15318       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15319       return Sext;
15320     }
15321
15322     // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15323     // lanes.
15324     assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15325            "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15326
15327     SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15328     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15329     return Shuff;
15330   }
15331
15332   // Redistribute the loaded elements into the different locations.
15333   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15334   for (unsigned i = 0; i != NumElems; ++i)
15335     ShuffleVec[i * SizeRatio] = i;
15336
15337   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15338                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15339
15340   // Bitcast to the requested type.
15341   Shuff = DAG.getBitcast(RegVT, Shuff);
15342   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15343   return Shuff;
15344 }
15345
15346 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15347 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15348 // from the AND / OR.
15349 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15350   Opc = Op.getOpcode();
15351   if (Opc != ISD::OR && Opc != ISD::AND)
15352     return false;
15353   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15354           Op.getOperand(0).hasOneUse() &&
15355           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15356           Op.getOperand(1).hasOneUse());
15357 }
15358
15359 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15360 // 1 and that the SETCC node has a single use.
15361 static bool isXor1OfSetCC(SDValue Op) {
15362   if (Op.getOpcode() != ISD::XOR)
15363     return false;
15364   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15365   if (N1C && N1C->getAPIntValue() == 1) {
15366     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15367       Op.getOperand(0).hasOneUse();
15368   }
15369   return false;
15370 }
15371
15372 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15373   bool addTest = true;
15374   SDValue Chain = Op.getOperand(0);
15375   SDValue Cond  = Op.getOperand(1);
15376   SDValue Dest  = Op.getOperand(2);
15377   SDLoc dl(Op);
15378   SDValue CC;
15379   bool Inverted = false;
15380
15381   if (Cond.getOpcode() == ISD::SETCC) {
15382     // Check for setcc([su]{add,sub,mul}o == 0).
15383     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15384         isa<ConstantSDNode>(Cond.getOperand(1)) &&
15385         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15386         Cond.getOperand(0).getResNo() == 1 &&
15387         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15388          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15389          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15390          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15391          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15392          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15393       Inverted = true;
15394       Cond = Cond.getOperand(0);
15395     } else {
15396       SDValue NewCond = LowerSETCC(Cond, DAG);
15397       if (NewCond.getNode())
15398         Cond = NewCond;
15399     }
15400   }
15401 #if 0
15402   // FIXME: LowerXALUO doesn't handle these!!
15403   else if (Cond.getOpcode() == X86ISD::ADD  ||
15404            Cond.getOpcode() == X86ISD::SUB  ||
15405            Cond.getOpcode() == X86ISD::SMUL ||
15406            Cond.getOpcode() == X86ISD::UMUL)
15407     Cond = LowerXALUO(Cond, DAG);
15408 #endif
15409
15410   // Look pass (and (setcc_carry (cmp ...)), 1).
15411   if (Cond.getOpcode() == ISD::AND &&
15412       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15413     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15414     if (C && C->getAPIntValue() == 1)
15415       Cond = Cond.getOperand(0);
15416   }
15417
15418   // If condition flag is set by a X86ISD::CMP, then use it as the condition
15419   // setting operand in place of the X86ISD::SETCC.
15420   unsigned CondOpcode = Cond.getOpcode();
15421   if (CondOpcode == X86ISD::SETCC ||
15422       CondOpcode == X86ISD::SETCC_CARRY) {
15423     CC = Cond.getOperand(0);
15424
15425     SDValue Cmp = Cond.getOperand(1);
15426     unsigned Opc = Cmp.getOpcode();
15427     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15428     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15429       Cond = Cmp;
15430       addTest = false;
15431     } else {
15432       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15433       default: break;
15434       case X86::COND_O:
15435       case X86::COND_B:
15436         // These can only come from an arithmetic instruction with overflow,
15437         // e.g. SADDO, UADDO.
15438         Cond = Cond.getNode()->getOperand(1);
15439         addTest = false;
15440         break;
15441       }
15442     }
15443   }
15444   CondOpcode = Cond.getOpcode();
15445   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15446       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15447       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15448        Cond.getOperand(0).getValueType() != MVT::i8)) {
15449     SDValue LHS = Cond.getOperand(0);
15450     SDValue RHS = Cond.getOperand(1);
15451     unsigned X86Opcode;
15452     unsigned X86Cond;
15453     SDVTList VTs;
15454     // Keep this in sync with LowerXALUO, otherwise we might create redundant
15455     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15456     // X86ISD::INC).
15457     switch (CondOpcode) {
15458     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15459     case ISD::SADDO:
15460       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15461         if (C->isOne()) {
15462           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15463           break;
15464         }
15465       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15466     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15467     case ISD::SSUBO:
15468       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15469         if (C->isOne()) {
15470           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15471           break;
15472         }
15473       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15474     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15475     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15476     default: llvm_unreachable("unexpected overflowing operator");
15477     }
15478     if (Inverted)
15479       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15480     if (CondOpcode == ISD::UMULO)
15481       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15482                           MVT::i32);
15483     else
15484       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15485
15486     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15487
15488     if (CondOpcode == ISD::UMULO)
15489       Cond = X86Op.getValue(2);
15490     else
15491       Cond = X86Op.getValue(1);
15492
15493     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15494     addTest = false;
15495   } else {
15496     unsigned CondOpc;
15497     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15498       SDValue Cmp = Cond.getOperand(0).getOperand(1);
15499       if (CondOpc == ISD::OR) {
15500         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15501         // two branches instead of an explicit OR instruction with a
15502         // separate test.
15503         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15504             isX86LogicalCmp(Cmp)) {
15505           CC = Cond.getOperand(0).getOperand(0);
15506           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15507                               Chain, Dest, CC, Cmp);
15508           CC = Cond.getOperand(1).getOperand(0);
15509           Cond = Cmp;
15510           addTest = false;
15511         }
15512       } else { // ISD::AND
15513         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15514         // two branches instead of an explicit AND instruction with a
15515         // separate test. However, we only do this if this block doesn't
15516         // have a fall-through edge, because this requires an explicit
15517         // jmp when the condition is false.
15518         if (Cmp == Cond.getOperand(1).getOperand(1) &&
15519             isX86LogicalCmp(Cmp) &&
15520             Op.getNode()->hasOneUse()) {
15521           X86::CondCode CCode =
15522             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15523           CCode = X86::GetOppositeBranchCondition(CCode);
15524           CC = DAG.getConstant(CCode, dl, MVT::i8);
15525           SDNode *User = *Op.getNode()->use_begin();
15526           // Look for an unconditional branch following this conditional branch.
15527           // We need this because we need to reverse the successors in order
15528           // to implement FCMP_OEQ.
15529           if (User->getOpcode() == ISD::BR) {
15530             SDValue FalseBB = User->getOperand(1);
15531             SDNode *NewBR =
15532               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15533             assert(NewBR == User);
15534             (void)NewBR;
15535             Dest = FalseBB;
15536
15537             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15538                                 Chain, Dest, CC, Cmp);
15539             X86::CondCode CCode =
15540               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15541             CCode = X86::GetOppositeBranchCondition(CCode);
15542             CC = DAG.getConstant(CCode, dl, MVT::i8);
15543             Cond = Cmp;
15544             addTest = false;
15545           }
15546         }
15547       }
15548     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15549       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15550       // It should be transformed during dag combiner except when the condition
15551       // is set by a arithmetics with overflow node.
15552       X86::CondCode CCode =
15553         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15554       CCode = X86::GetOppositeBranchCondition(CCode);
15555       CC = DAG.getConstant(CCode, dl, MVT::i8);
15556       Cond = Cond.getOperand(0).getOperand(1);
15557       addTest = false;
15558     } else if (Cond.getOpcode() == ISD::SETCC &&
15559                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15560       // For FCMP_OEQ, we can emit
15561       // two branches instead of an explicit AND instruction with a
15562       // separate test. However, we only do this if this block doesn't
15563       // have a fall-through edge, because this requires an explicit
15564       // jmp when the condition is false.
15565       if (Op.getNode()->hasOneUse()) {
15566         SDNode *User = *Op.getNode()->use_begin();
15567         // Look for an unconditional branch following this conditional branch.
15568         // We need this because we need to reverse the successors in order
15569         // to implement FCMP_OEQ.
15570         if (User->getOpcode() == ISD::BR) {
15571           SDValue FalseBB = User->getOperand(1);
15572           SDNode *NewBR =
15573             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15574           assert(NewBR == User);
15575           (void)NewBR;
15576           Dest = FalseBB;
15577
15578           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15579                                     Cond.getOperand(0), Cond.getOperand(1));
15580           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15581           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15582           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15583                               Chain, Dest, CC, Cmp);
15584           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15585           Cond = Cmp;
15586           addTest = false;
15587         }
15588       }
15589     } else if (Cond.getOpcode() == ISD::SETCC &&
15590                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15591       // For FCMP_UNE, we can emit
15592       // two branches instead of an explicit AND instruction with a
15593       // separate test. However, we only do this if this block doesn't
15594       // have a fall-through edge, because this requires an explicit
15595       // jmp when the condition is false.
15596       if (Op.getNode()->hasOneUse()) {
15597         SDNode *User = *Op.getNode()->use_begin();
15598         // Look for an unconditional branch following this conditional branch.
15599         // We need this because we need to reverse the successors in order
15600         // to implement FCMP_UNE.
15601         if (User->getOpcode() == ISD::BR) {
15602           SDValue FalseBB = User->getOperand(1);
15603           SDNode *NewBR =
15604             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15605           assert(NewBR == User);
15606           (void)NewBR;
15607
15608           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15609                                     Cond.getOperand(0), Cond.getOperand(1));
15610           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15611           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15612           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15613                               Chain, Dest, CC, Cmp);
15614           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15615           Cond = Cmp;
15616           addTest = false;
15617           Dest = FalseBB;
15618         }
15619       }
15620     }
15621   }
15622
15623   if (addTest) {
15624     // Look pass the truncate if the high bits are known zero.
15625     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15626         Cond = Cond.getOperand(0);
15627
15628     // We know the result of AND is compared against zero. Try to match
15629     // it to BT.
15630     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15631       if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15632         CC = NewSetCC.getOperand(0);
15633         Cond = NewSetCC.getOperand(1);
15634         addTest = false;
15635       }
15636     }
15637   }
15638
15639   if (addTest) {
15640     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15641     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15642     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15643   }
15644   Cond = ConvertCmpIfNecessary(Cond, DAG);
15645   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15646                      Chain, Dest, CC, Cond);
15647 }
15648
15649 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15650 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15651 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15652 // that the guard pages used by the OS virtual memory manager are allocated in
15653 // correct sequence.
15654 SDValue
15655 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15656                                            SelectionDAG &DAG) const {
15657   MachineFunction &MF = DAG.getMachineFunction();
15658   bool SplitStack = MF.shouldSplitStack();
15659   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15660                SplitStack;
15661   SDLoc dl(Op);
15662
15663   if (!Lower) {
15664     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15665     SDNode* Node = Op.getNode();
15666
15667     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15668     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15669         " not tell us which reg is the stack pointer!");
15670     EVT VT = Node->getValueType(0);
15671     SDValue Tmp1 = SDValue(Node, 0);
15672     SDValue Tmp2 = SDValue(Node, 1);
15673     SDValue Tmp3 = Node->getOperand(2);
15674     SDValue Chain = Tmp1.getOperand(0);
15675
15676     // Chain the dynamic stack allocation so that it doesn't modify the stack
15677     // pointer when other instructions are using the stack.
15678     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15679         SDLoc(Node));
15680
15681     SDValue Size = Tmp2.getOperand(1);
15682     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15683     Chain = SP.getValue(1);
15684     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15685     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15686     unsigned StackAlign = TFI.getStackAlignment();
15687     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15688     if (Align > StackAlign)
15689       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15690           DAG.getConstant(-(uint64_t)Align, dl, VT));
15691     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15692
15693     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15694         DAG.getIntPtrConstant(0, dl, true), SDValue(),
15695         SDLoc(Node));
15696
15697     SDValue Ops[2] = { Tmp1, Tmp2 };
15698     return DAG.getMergeValues(Ops, dl);
15699   }
15700
15701   // Get the inputs.
15702   SDValue Chain = Op.getOperand(0);
15703   SDValue Size  = Op.getOperand(1);
15704   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15705   EVT VT = Op.getNode()->getValueType(0);
15706
15707   bool Is64Bit = Subtarget->is64Bit();
15708   MVT SPTy = getPointerTy(DAG.getDataLayout());
15709
15710   if (SplitStack) {
15711     MachineRegisterInfo &MRI = MF.getRegInfo();
15712
15713     if (Is64Bit) {
15714       // The 64 bit implementation of segmented stacks needs to clobber both r10
15715       // r11. This makes it impossible to use it along with nested parameters.
15716       const Function *F = MF.getFunction();
15717
15718       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15719            I != E; ++I)
15720         if (I->hasNestAttr())
15721           report_fatal_error("Cannot use segmented stacks with functions that "
15722                              "have nested arguments.");
15723     }
15724
15725     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15726     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15727     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15728     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15729                                 DAG.getRegister(Vreg, SPTy));
15730     SDValue Ops1[2] = { Value, Chain };
15731     return DAG.getMergeValues(Ops1, dl);
15732   } else {
15733     SDValue Flag;
15734     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15735
15736     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15737     Flag = Chain.getValue(1);
15738     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15739
15740     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15741
15742     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15743     unsigned SPReg = RegInfo->getStackRegister();
15744     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15745     Chain = SP.getValue(1);
15746
15747     if (Align) {
15748       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15749                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15750       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15751     }
15752
15753     SDValue Ops1[2] = { SP, Chain };
15754     return DAG.getMergeValues(Ops1, dl);
15755   }
15756 }
15757
15758 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15759   MachineFunction &MF = DAG.getMachineFunction();
15760   auto PtrVT = getPointerTy(MF.getDataLayout());
15761   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15762
15763   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15764   SDLoc DL(Op);
15765
15766   if (!Subtarget->is64Bit() ||
15767       Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15768     // vastart just stores the address of the VarArgsFrameIndex slot into the
15769     // memory location argument.
15770     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15771     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15772                         MachinePointerInfo(SV), false, false, 0);
15773   }
15774
15775   // __va_list_tag:
15776   //   gp_offset         (0 - 6 * 8)
15777   //   fp_offset         (48 - 48 + 8 * 16)
15778   //   overflow_arg_area (point to parameters coming in memory).
15779   //   reg_save_area
15780   SmallVector<SDValue, 8> MemOps;
15781   SDValue FIN = Op.getOperand(1);
15782   // Store gp_offset
15783   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15784                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15785                                                DL, MVT::i32),
15786                                FIN, MachinePointerInfo(SV), false, false, 0);
15787   MemOps.push_back(Store);
15788
15789   // Store fp_offset
15790   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15791   Store = DAG.getStore(Op.getOperand(0), DL,
15792                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15793                                        MVT::i32),
15794                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15795   MemOps.push_back(Store);
15796
15797   // Store ptr to overflow_arg_area
15798   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15799   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15800   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15801                        MachinePointerInfo(SV, 8),
15802                        false, false, 0);
15803   MemOps.push_back(Store);
15804
15805   // Store ptr to reg_save_area.
15806   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15807       Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15808   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15809   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15810       SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15811   MemOps.push_back(Store);
15812   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15813 }
15814
15815 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15816   assert(Subtarget->is64Bit() &&
15817          "LowerVAARG only handles 64-bit va_arg!");
15818   assert(Op.getNode()->getNumOperands() == 4);
15819
15820   MachineFunction &MF = DAG.getMachineFunction();
15821   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15822     // The Win64 ABI uses char* instead of a structure.
15823     return DAG.expandVAArg(Op.getNode());
15824
15825   SDValue Chain = Op.getOperand(0);
15826   SDValue SrcPtr = Op.getOperand(1);
15827   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15828   unsigned Align = Op.getConstantOperandVal(3);
15829   SDLoc dl(Op);
15830
15831   EVT ArgVT = Op.getNode()->getValueType(0);
15832   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15833   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15834   uint8_t ArgMode;
15835
15836   // Decide which area this value should be read from.
15837   // TODO: Implement the AMD64 ABI in its entirety. This simple
15838   // selection mechanism works only for the basic types.
15839   if (ArgVT == MVT::f80) {
15840     llvm_unreachable("va_arg for f80 not yet implemented");
15841   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15842     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15843   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15844     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15845   } else {
15846     llvm_unreachable("Unhandled argument type in LowerVAARG");
15847   }
15848
15849   if (ArgMode == 2) {
15850     // Sanity Check: Make sure using fp_offset makes sense.
15851     assert(!Subtarget->useSoftFloat() &&
15852            !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15853            Subtarget->hasSSE1());
15854   }
15855
15856   // Insert VAARG_64 node into the DAG
15857   // VAARG_64 returns two values: Variable Argument Address, Chain
15858   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15859                        DAG.getConstant(ArgMode, dl, MVT::i8),
15860                        DAG.getConstant(Align, dl, MVT::i32)};
15861   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15862   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15863                                           VTs, InstOps, MVT::i64,
15864                                           MachinePointerInfo(SV),
15865                                           /*Align=*/0,
15866                                           /*Volatile=*/false,
15867                                           /*ReadMem=*/true,
15868                                           /*WriteMem=*/true);
15869   Chain = VAARG.getValue(1);
15870
15871   // Load the next argument and return it
15872   return DAG.getLoad(ArgVT, dl,
15873                      Chain,
15874                      VAARG,
15875                      MachinePointerInfo(),
15876                      false, false, false, 0);
15877 }
15878
15879 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15880                            SelectionDAG &DAG) {
15881   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15882   // where a va_list is still an i8*.
15883   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15884   if (Subtarget->isCallingConvWin64(
15885         DAG.getMachineFunction().getFunction()->getCallingConv()))
15886     // Probably a Win64 va_copy.
15887     return DAG.expandVACopy(Op.getNode());
15888
15889   SDValue Chain = Op.getOperand(0);
15890   SDValue DstPtr = Op.getOperand(1);
15891   SDValue SrcPtr = Op.getOperand(2);
15892   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15893   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15894   SDLoc DL(Op);
15895
15896   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15897                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15898                        false, false,
15899                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15900 }
15901
15902 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15903 // amount is a constant. Takes immediate version of shift as input.
15904 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15905                                           SDValue SrcOp, uint64_t ShiftAmt,
15906                                           SelectionDAG &DAG) {
15907   MVT ElementType = VT.getVectorElementType();
15908
15909   // Fold this packed shift into its first operand if ShiftAmt is 0.
15910   if (ShiftAmt == 0)
15911     return SrcOp;
15912
15913   // Check for ShiftAmt >= element width
15914   if (ShiftAmt >= ElementType.getSizeInBits()) {
15915     if (Opc == X86ISD::VSRAI)
15916       ShiftAmt = ElementType.getSizeInBits() - 1;
15917     else
15918       return DAG.getConstant(0, dl, VT);
15919   }
15920
15921   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15922          && "Unknown target vector shift-by-constant node");
15923
15924   // Fold this packed vector shift into a build vector if SrcOp is a
15925   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15926   if (VT == SrcOp.getSimpleValueType() &&
15927       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15928     SmallVector<SDValue, 8> Elts;
15929     unsigned NumElts = SrcOp->getNumOperands();
15930     ConstantSDNode *ND;
15931
15932     switch(Opc) {
15933     default: llvm_unreachable(nullptr);
15934     case X86ISD::VSHLI:
15935       for (unsigned i=0; i!=NumElts; ++i) {
15936         SDValue CurrentOp = SrcOp->getOperand(i);
15937         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15938           Elts.push_back(CurrentOp);
15939           continue;
15940         }
15941         ND = cast<ConstantSDNode>(CurrentOp);
15942         const APInt &C = ND->getAPIntValue();
15943         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15944       }
15945       break;
15946     case X86ISD::VSRLI:
15947       for (unsigned i=0; i!=NumElts; ++i) {
15948         SDValue CurrentOp = SrcOp->getOperand(i);
15949         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15950           Elts.push_back(CurrentOp);
15951           continue;
15952         }
15953         ND = cast<ConstantSDNode>(CurrentOp);
15954         const APInt &C = ND->getAPIntValue();
15955         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15956       }
15957       break;
15958     case X86ISD::VSRAI:
15959       for (unsigned i=0; i!=NumElts; ++i) {
15960         SDValue CurrentOp = SrcOp->getOperand(i);
15961         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15962           Elts.push_back(CurrentOp);
15963           continue;
15964         }
15965         ND = cast<ConstantSDNode>(CurrentOp);
15966         const APInt &C = ND->getAPIntValue();
15967         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15968       }
15969       break;
15970     }
15971
15972     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15973   }
15974
15975   return DAG.getNode(Opc, dl, VT, SrcOp,
15976                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15977 }
15978
15979 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15980 // may or may not be a constant. Takes immediate version of shift as input.
15981 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15982                                    SDValue SrcOp, SDValue ShAmt,
15983                                    SelectionDAG &DAG) {
15984   MVT SVT = ShAmt.getSimpleValueType();
15985   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15986
15987   // Catch shift-by-constant.
15988   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15989     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15990                                       CShAmt->getZExtValue(), DAG);
15991
15992   // Change opcode to non-immediate version
15993   switch (Opc) {
15994     default: llvm_unreachable("Unknown target vector shift node");
15995     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15996     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15997     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15998   }
15999
16000   const X86Subtarget &Subtarget =
16001       static_cast<const X86Subtarget &>(DAG.getSubtarget());
16002   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16003       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16004     // Let the shuffle legalizer expand this shift amount node.
16005     SDValue Op0 = ShAmt.getOperand(0);
16006     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16007     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16008   } else {
16009     // Need to build a vector containing shift amount.
16010     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16011     SmallVector<SDValue, 4> ShOps;
16012     ShOps.push_back(ShAmt);
16013     if (SVT == MVT::i32) {
16014       ShOps.push_back(DAG.getConstant(0, dl, SVT));
16015       ShOps.push_back(DAG.getUNDEF(SVT));
16016     }
16017     ShOps.push_back(DAG.getUNDEF(SVT));
16018
16019     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16020     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16021   }
16022
16023   // The return type has to be a 128-bit type with the same element
16024   // type as the input type.
16025   MVT EltVT = VT.getVectorElementType();
16026   MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16027
16028   ShAmt = DAG.getBitcast(ShVT, ShAmt);
16029   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16030 }
16031
16032 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16033 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16034 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16035 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16036                                     SDValue PreservedSrc,
16037                                     const X86Subtarget *Subtarget,
16038                                     SelectionDAG &DAG) {
16039     MVT VT = Op.getSimpleValueType();
16040     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16041     SDValue VMask;
16042     unsigned OpcodeSelect = ISD::VSELECT;
16043     SDLoc dl(Op);
16044
16045     if (isAllOnes(Mask))
16046       return Op;
16047
16048     if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16049       MVT newMaskVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16050       VMask = DAG.getBitcast(MaskVT,
16051                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
16052     } else {
16053       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16054                                        Mask.getSimpleValueType().getSizeInBits());
16055       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16056       // are extracted by EXTRACT_SUBVECTOR.
16057       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16058                           DAG.getBitcast(BitcastVT, Mask),
16059                           DAG.getIntPtrConstant(0, dl));
16060     }
16061
16062     switch (Op.getOpcode()) {
16063     default: break;
16064     case X86ISD::PCMPEQM:
16065     case X86ISD::PCMPGTM:
16066     case X86ISD::CMPM:
16067     case X86ISD::CMPMU:
16068       return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16069     case X86ISD::VFPCLASS:
16070       return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16071     case X86ISD::VTRUNC:
16072     case X86ISD::VTRUNCS:
16073     case X86ISD::VTRUNCUS:
16074       // We can't use ISD::VSELECT here because it is not always "Legal"
16075       // for the destination type. For example vpmovqb require only AVX512
16076       // and vselect that can operate on byte element type require BWI
16077       OpcodeSelect = X86ISD::SELECT;
16078       break;
16079     }
16080     if (PreservedSrc.getOpcode() == ISD::UNDEF)
16081       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16082     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16083 }
16084
16085 /// \brief Creates an SDNode for a predicated scalar operation.
16086 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16087 /// The mask is coming as MVT::i8 and it should be truncated
16088 /// to MVT::i1 while lowering masking intrinsics.
16089 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16090 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16091 /// for a scalar instruction.
16092 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16093                                     SDValue PreservedSrc,
16094                                     const X86Subtarget *Subtarget,
16095                                     SelectionDAG &DAG) {
16096   if (isAllOnes(Mask))
16097     return Op;
16098
16099   MVT VT = Op.getSimpleValueType();
16100   SDLoc dl(Op);
16101   // The mask should be of type MVT::i1
16102   SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16103
16104   if (Op.getOpcode() == X86ISD::FSETCC)
16105     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16106   if (Op.getOpcode() == X86ISD::VFPCLASS)
16107     return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16108
16109   if (PreservedSrc.getOpcode() == ISD::UNDEF)
16110     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16111   return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16112 }
16113
16114 static int getSEHRegistrationNodeSize(const Function *Fn) {
16115   if (!Fn->hasPersonalityFn())
16116     report_fatal_error(
16117         "querying registration node size for function without personality");
16118   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16119   // WinEHStatePass for the full struct definition.
16120   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16121   case EHPersonality::MSVC_X86SEH: return 24;
16122   case EHPersonality::MSVC_CXX: return 16;
16123   default: break;
16124   }
16125   report_fatal_error("can only recover FP for MSVC EH personality functions");
16126 }
16127
16128 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
16129 /// function or when returning to a parent frame after catching an exception, we
16130 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16131 /// Here's the math:
16132 ///   RegNodeBase = EntryEBP - RegNodeSize
16133 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
16134 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16135 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16136 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16137                                    SDValue EntryEBP) {
16138   MachineFunction &MF = DAG.getMachineFunction();
16139   SDLoc dl;
16140
16141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16142   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16143
16144   // It's possible that the parent function no longer has a personality function
16145   // if the exceptional code was optimized away, in which case we just return
16146   // the incoming EBP.
16147   if (!Fn->hasPersonalityFn())
16148     return EntryEBP;
16149
16150   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16151
16152   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16153   // registration.
16154   MCSymbol *OffsetSym =
16155       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16156           GlobalValue::getRealLinkageName(Fn->getName()));
16157   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16158   SDValue RegNodeFrameOffset =
16159       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16160
16161   // RegNodeBase = EntryEBP - RegNodeSize
16162   // ParentFP = RegNodeBase - RegNodeFrameOffset
16163   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16164                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
16165   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16166 }
16167
16168 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16169                                        SelectionDAG &DAG) {
16170   SDLoc dl(Op);
16171   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16172   MVT VT = Op.getSimpleValueType();
16173   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16174   if (IntrData) {
16175     switch(IntrData->Type) {
16176     case INTR_TYPE_1OP:
16177       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16178     case INTR_TYPE_2OP:
16179       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16180         Op.getOperand(2));
16181     case INTR_TYPE_2OP_IMM8:
16182       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16183                          DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16184     case INTR_TYPE_3OP:
16185       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16186         Op.getOperand(2), Op.getOperand(3));
16187     case INTR_TYPE_4OP:
16188       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16189         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16190     case INTR_TYPE_1OP_MASK_RM: {
16191       SDValue Src = Op.getOperand(1);
16192       SDValue PassThru = Op.getOperand(2);
16193       SDValue Mask = Op.getOperand(3);
16194       SDValue RoundingMode;
16195       // We allways add rounding mode to the Node.
16196       // If the rounding mode is not specified, we add the
16197       // "current direction" mode.
16198       if (Op.getNumOperands() == 4)
16199         RoundingMode =
16200           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16201       else
16202         RoundingMode = Op.getOperand(4);
16203       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16204       if (IntrWithRoundingModeOpcode != 0)
16205         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16206             X86::STATIC_ROUNDING::CUR_DIRECTION)
16207           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16208                                       dl, Op.getValueType(), Src, RoundingMode),
16209                                       Mask, PassThru, Subtarget, DAG);
16210       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16211                                               RoundingMode),
16212                                   Mask, PassThru, Subtarget, DAG);
16213     }
16214     case INTR_TYPE_1OP_MASK: {
16215       SDValue Src = Op.getOperand(1);
16216       SDValue PassThru = Op.getOperand(2);
16217       SDValue Mask = Op.getOperand(3);
16218       // We add rounding mode to the Node when
16219       //   - RM Opcode is specified and
16220       //   - RM is not "current direction".
16221       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16222       if (IntrWithRoundingModeOpcode != 0) {
16223         SDValue Rnd = Op.getOperand(4);
16224         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16225         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16226           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16227                                       dl, Op.getValueType(),
16228                                       Src, Rnd),
16229                                       Mask, PassThru, Subtarget, DAG);
16230         }
16231       }
16232       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16233                                   Mask, PassThru, Subtarget, DAG);
16234     }
16235     case INTR_TYPE_SCALAR_MASK: {
16236       SDValue Src1 = Op.getOperand(1);
16237       SDValue Src2 = Op.getOperand(2);
16238       SDValue passThru = Op.getOperand(3);
16239       SDValue Mask = Op.getOperand(4);
16240       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16241                                   Mask, passThru, Subtarget, DAG);
16242     }
16243     case INTR_TYPE_SCALAR_MASK_RM: {
16244       SDValue Src1 = Op.getOperand(1);
16245       SDValue Src2 = Op.getOperand(2);
16246       SDValue Src0 = Op.getOperand(3);
16247       SDValue Mask = Op.getOperand(4);
16248       // There are 2 kinds of intrinsics in this group:
16249       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16250       // (2) With rounding mode and sae - 7 operands.
16251       if (Op.getNumOperands() == 6) {
16252         SDValue Sae  = Op.getOperand(5);
16253         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16254         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16255                                                 Sae),
16256                                     Mask, Src0, Subtarget, DAG);
16257       }
16258       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16259       SDValue RoundingMode  = Op.getOperand(5);
16260       SDValue Sae  = Op.getOperand(6);
16261       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16262                                               RoundingMode, Sae),
16263                                   Mask, Src0, Subtarget, DAG);
16264     }
16265     case INTR_TYPE_2OP_MASK:
16266     case INTR_TYPE_2OP_IMM8_MASK: {
16267       SDValue Src1 = Op.getOperand(1);
16268       SDValue Src2 = Op.getOperand(2);
16269       SDValue PassThru = Op.getOperand(3);
16270       SDValue Mask = Op.getOperand(4);
16271
16272       if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16273         Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16274
16275       // We specify 2 possible opcodes for intrinsics with rounding modes.
16276       // First, we check if the intrinsic may have non-default rounding mode,
16277       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16278       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16279       if (IntrWithRoundingModeOpcode != 0) {
16280         SDValue Rnd = Op.getOperand(5);
16281         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16282         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16283           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16284                                       dl, Op.getValueType(),
16285                                       Src1, Src2, Rnd),
16286                                       Mask, PassThru, Subtarget, DAG);
16287         }
16288       }
16289       // TODO: Intrinsics should have fast-math-flags to propagate.
16290       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16291                                   Mask, PassThru, Subtarget, DAG);
16292     }
16293     case INTR_TYPE_2OP_MASK_RM: {
16294       SDValue Src1 = Op.getOperand(1);
16295       SDValue Src2 = Op.getOperand(2);
16296       SDValue PassThru = Op.getOperand(3);
16297       SDValue Mask = Op.getOperand(4);
16298       // We specify 2 possible modes for intrinsics, with/without rounding
16299       // modes.
16300       // First, we check if the intrinsic have rounding mode (6 operands),
16301       // if not, we set rounding mode to "current".
16302       SDValue Rnd;
16303       if (Op.getNumOperands() == 6)
16304         Rnd = Op.getOperand(5);
16305       else
16306         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16307       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16308                                               Src1, Src2, Rnd),
16309                                   Mask, PassThru, Subtarget, DAG);
16310     }
16311     case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16312       SDValue Src1 = Op.getOperand(1);
16313       SDValue Src2 = Op.getOperand(2);
16314       SDValue Src3 = Op.getOperand(3);
16315       SDValue PassThru = Op.getOperand(4);
16316       SDValue Mask = Op.getOperand(5);
16317       SDValue Sae  = Op.getOperand(6);
16318
16319       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16320                                               Src2, Src3, Sae),
16321                                   Mask, PassThru, Subtarget, DAG);
16322     }
16323     case INTR_TYPE_3OP_MASK_RM: {
16324       SDValue Src1 = Op.getOperand(1);
16325       SDValue Src2 = Op.getOperand(2);
16326       SDValue Imm = Op.getOperand(3);
16327       SDValue PassThru = Op.getOperand(4);
16328       SDValue Mask = Op.getOperand(5);
16329       // We specify 2 possible modes for intrinsics, with/without rounding
16330       // modes.
16331       // First, we check if the intrinsic have rounding mode (7 operands),
16332       // if not, we set rounding mode to "current".
16333       SDValue Rnd;
16334       if (Op.getNumOperands() == 7)
16335         Rnd = Op.getOperand(6);
16336       else
16337         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16338       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16339         Src1, Src2, Imm, Rnd),
16340         Mask, PassThru, Subtarget, DAG);
16341     }
16342     case INTR_TYPE_3OP_IMM8_MASK:
16343     case INTR_TYPE_3OP_MASK:
16344     case INSERT_SUBVEC: {
16345       SDValue Src1 = Op.getOperand(1);
16346       SDValue Src2 = Op.getOperand(2);
16347       SDValue Src3 = Op.getOperand(3);
16348       SDValue PassThru = Op.getOperand(4);
16349       SDValue Mask = Op.getOperand(5);
16350
16351       if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16352         Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16353       else if (IntrData->Type == INSERT_SUBVEC) {
16354         // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16355         assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16356         unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16357         Imm *= Src2.getSimpleValueType().getVectorNumElements();
16358         Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16359       }
16360
16361       // We specify 2 possible opcodes for intrinsics with rounding modes.
16362       // First, we check if the intrinsic may have non-default rounding mode,
16363       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16364       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16365       if (IntrWithRoundingModeOpcode != 0) {
16366         SDValue Rnd = Op.getOperand(6);
16367         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16368         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16369           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16370                                       dl, Op.getValueType(),
16371                                       Src1, Src2, Src3, Rnd),
16372                                       Mask, PassThru, Subtarget, DAG);
16373         }
16374       }
16375       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16376                                               Src1, Src2, Src3),
16377                                   Mask, PassThru, Subtarget, DAG);
16378     }
16379     case VPERM_3OP_MASKZ:
16380     case VPERM_3OP_MASK:{
16381       // Src2 is the PassThru
16382       SDValue Src1 = Op.getOperand(1);
16383       SDValue Src2 = Op.getOperand(2);
16384       SDValue Src3 = Op.getOperand(3);
16385       SDValue Mask = Op.getOperand(4);
16386       MVT VT = Op.getSimpleValueType();
16387       SDValue PassThru = SDValue();
16388
16389       // set PassThru element
16390       if (IntrData->Type == VPERM_3OP_MASKZ)
16391         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16392       else
16393         PassThru = Src2;
16394
16395       // Swap Src1 and Src2 in the node creation
16396       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16397                                               dl, Op.getValueType(),
16398                                               Src2, Src1, Src3),
16399                                   Mask, PassThru, Subtarget, DAG);
16400     }
16401     case FMA_OP_MASK3:
16402     case FMA_OP_MASKZ:
16403     case FMA_OP_MASK: {
16404       SDValue Src1 = Op.getOperand(1);
16405       SDValue Src2 = Op.getOperand(2);
16406       SDValue Src3 = Op.getOperand(3);
16407       SDValue Mask = Op.getOperand(4);
16408       MVT VT = Op.getSimpleValueType();
16409       SDValue PassThru = SDValue();
16410
16411       // set PassThru element
16412       if (IntrData->Type == FMA_OP_MASKZ)
16413         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16414       else if (IntrData->Type == FMA_OP_MASK3)
16415         PassThru = Src3;
16416       else
16417         PassThru = Src1;
16418
16419       // We specify 2 possible opcodes for intrinsics with rounding modes.
16420       // First, we check if the intrinsic may have non-default rounding mode,
16421       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16422       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16423       if (IntrWithRoundingModeOpcode != 0) {
16424         SDValue Rnd = Op.getOperand(5);
16425         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16426             X86::STATIC_ROUNDING::CUR_DIRECTION)
16427           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16428                                                   dl, Op.getValueType(),
16429                                                   Src1, Src2, Src3, Rnd),
16430                                       Mask, PassThru, Subtarget, DAG);
16431       }
16432       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16433                                               dl, Op.getValueType(),
16434                                               Src1, Src2, Src3),
16435                                   Mask, PassThru, Subtarget, DAG);
16436     }
16437     case TERLOG_OP_MASK:
16438     case TERLOG_OP_MASKZ: {
16439       SDValue Src1 = Op.getOperand(1);
16440       SDValue Src2 = Op.getOperand(2);
16441       SDValue Src3 = Op.getOperand(3);
16442       SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16443       SDValue Mask = Op.getOperand(5);
16444       MVT VT = Op.getSimpleValueType();
16445       SDValue PassThru = Src1;
16446       // Set PassThru element.
16447       if (IntrData->Type == TERLOG_OP_MASKZ)
16448         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16449
16450       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16451                                               Src1, Src2, Src3, Src4),
16452                                   Mask, PassThru, Subtarget, DAG);
16453     }
16454     case FPCLASS: {
16455       // FPclass intrinsics with mask
16456        SDValue Src1 = Op.getOperand(1);
16457        MVT VT = Src1.getSimpleValueType();
16458        MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16459        SDValue Imm = Op.getOperand(2);
16460        SDValue Mask = Op.getOperand(3);
16461        MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16462                                      Mask.getSimpleValueType().getSizeInBits());
16463        SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16464        SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16465                                                  DAG.getTargetConstant(0, dl, MaskVT),
16466                                                  Subtarget, DAG);
16467        SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16468                                  DAG.getUNDEF(BitcastVT), FPclassMask,
16469                                  DAG.getIntPtrConstant(0, dl));
16470        return DAG.getBitcast(Op.getValueType(), Res);
16471     }
16472     case FPCLASSS: {
16473       SDValue Src1 = Op.getOperand(1);
16474       SDValue Imm = Op.getOperand(2);
16475       SDValue Mask = Op.getOperand(3);
16476       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16477       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16478         DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16479       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16480     }
16481     case CMP_MASK:
16482     case CMP_MASK_CC: {
16483       // Comparison intrinsics with masks.
16484       // Example of transformation:
16485       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16486       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16487       // (i8 (bitcast
16488       //   (v8i1 (insert_subvector undef,
16489       //           (v2i1 (and (PCMPEQM %a, %b),
16490       //                      (extract_subvector
16491       //                         (v8i1 (bitcast %mask)), 0))), 0))))
16492       MVT VT = Op.getOperand(1).getSimpleValueType();
16493       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16494       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16495       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16496                                        Mask.getSimpleValueType().getSizeInBits());
16497       SDValue Cmp;
16498       if (IntrData->Type == CMP_MASK_CC) {
16499         SDValue CC = Op.getOperand(3);
16500         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16501         // We specify 2 possible opcodes for intrinsics with rounding modes.
16502         // First, we check if the intrinsic may have non-default rounding mode,
16503         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16504         if (IntrData->Opc1 != 0) {
16505           SDValue Rnd = Op.getOperand(5);
16506           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16507               X86::STATIC_ROUNDING::CUR_DIRECTION)
16508             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16509                               Op.getOperand(2), CC, Rnd);
16510         }
16511         //default rounding mode
16512         if(!Cmp.getNode())
16513             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16514                               Op.getOperand(2), CC);
16515
16516       } else {
16517         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16518         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16519                           Op.getOperand(2));
16520       }
16521       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16522                                              DAG.getTargetConstant(0, dl,
16523                                                                    MaskVT),
16524                                              Subtarget, DAG);
16525       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16526                                 DAG.getUNDEF(BitcastVT), CmpMask,
16527                                 DAG.getIntPtrConstant(0, dl));
16528       return DAG.getBitcast(Op.getValueType(), Res);
16529     }
16530     case CMP_MASK_SCALAR_CC: {
16531       SDValue Src1 = Op.getOperand(1);
16532       SDValue Src2 = Op.getOperand(2);
16533       SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16534       SDValue Mask = Op.getOperand(4);
16535
16536       SDValue Cmp;
16537       if (IntrData->Opc1 != 0) {
16538         SDValue Rnd = Op.getOperand(5);
16539         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16540             X86::STATIC_ROUNDING::CUR_DIRECTION)
16541           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16542       }
16543       //default rounding mode
16544       if(!Cmp.getNode())
16545         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16546
16547       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16548                                              DAG.getTargetConstant(0, dl,
16549                                                                    MVT::i1),
16550                                              Subtarget, DAG);
16551
16552       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16553                          DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16554                          DAG.getValueType(MVT::i1));
16555     }
16556     case COMI: { // Comparison intrinsics
16557       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16558       SDValue LHS = Op.getOperand(1);
16559       SDValue RHS = Op.getOperand(2);
16560       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16561       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16562       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16563       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16564                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16565       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16566     }
16567     case VSHIFT:
16568       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16569                                  Op.getOperand(1), Op.getOperand(2), DAG);
16570     case VSHIFT_MASK:
16571       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16572                                                       Op.getSimpleValueType(),
16573                                                       Op.getOperand(1),
16574                                                       Op.getOperand(2), DAG),
16575                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
16576                                   DAG);
16577     case COMPRESS_EXPAND_IN_REG: {
16578       SDValue Mask = Op.getOperand(3);
16579       SDValue DataToCompress = Op.getOperand(1);
16580       SDValue PassThru = Op.getOperand(2);
16581       if (isAllOnes(Mask)) // return data as is
16582         return Op.getOperand(1);
16583
16584       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16585                                               DataToCompress),
16586                                   Mask, PassThru, Subtarget, DAG);
16587     }
16588     case BROADCASTM: {
16589       SDValue Mask = Op.getOperand(1);
16590       MVT MaskVT = MVT::getVectorVT(MVT::i1, Mask.getSimpleValueType().getSizeInBits());
16591       Mask = DAG.getBitcast(MaskVT, Mask);
16592       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16593     }
16594     case BLEND: {
16595       SDValue Mask = Op.getOperand(3);
16596       MVT VT = Op.getSimpleValueType();
16597       MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16598       MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16599                                        Mask.getSimpleValueType().getSizeInBits());
16600       SDLoc dl(Op);
16601       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16602                                   DAG.getBitcast(BitcastVT, Mask),
16603                                   DAG.getIntPtrConstant(0, dl));
16604       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16605                          Op.getOperand(2));
16606     }
16607     default:
16608       break;
16609     }
16610   }
16611
16612   switch (IntNo) {
16613   default: return SDValue();    // Don't custom lower most intrinsics.
16614
16615   case Intrinsic::x86_avx2_permd:
16616   case Intrinsic::x86_avx2_permps:
16617     // Operands intentionally swapped. Mask is last operand to intrinsic,
16618     // but second operand for node/instruction.
16619     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16620                        Op.getOperand(2), Op.getOperand(1));
16621
16622   // ptest and testp intrinsics. The intrinsic these come from are designed to
16623   // return an integer value, not just an instruction so lower it to the ptest
16624   // or testp pattern and a setcc for the result.
16625   case Intrinsic::x86_sse41_ptestz:
16626   case Intrinsic::x86_sse41_ptestc:
16627   case Intrinsic::x86_sse41_ptestnzc:
16628   case Intrinsic::x86_avx_ptestz_256:
16629   case Intrinsic::x86_avx_ptestc_256:
16630   case Intrinsic::x86_avx_ptestnzc_256:
16631   case Intrinsic::x86_avx_vtestz_ps:
16632   case Intrinsic::x86_avx_vtestc_ps:
16633   case Intrinsic::x86_avx_vtestnzc_ps:
16634   case Intrinsic::x86_avx_vtestz_pd:
16635   case Intrinsic::x86_avx_vtestc_pd:
16636   case Intrinsic::x86_avx_vtestnzc_pd:
16637   case Intrinsic::x86_avx_vtestz_ps_256:
16638   case Intrinsic::x86_avx_vtestc_ps_256:
16639   case Intrinsic::x86_avx_vtestnzc_ps_256:
16640   case Intrinsic::x86_avx_vtestz_pd_256:
16641   case Intrinsic::x86_avx_vtestc_pd_256:
16642   case Intrinsic::x86_avx_vtestnzc_pd_256: {
16643     bool IsTestPacked = false;
16644     unsigned X86CC;
16645     switch (IntNo) {
16646     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16647     case Intrinsic::x86_avx_vtestz_ps:
16648     case Intrinsic::x86_avx_vtestz_pd:
16649     case Intrinsic::x86_avx_vtestz_ps_256:
16650     case Intrinsic::x86_avx_vtestz_pd_256:
16651       IsTestPacked = true; // Fallthrough
16652     case Intrinsic::x86_sse41_ptestz:
16653     case Intrinsic::x86_avx_ptestz_256:
16654       // ZF = 1
16655       X86CC = X86::COND_E;
16656       break;
16657     case Intrinsic::x86_avx_vtestc_ps:
16658     case Intrinsic::x86_avx_vtestc_pd:
16659     case Intrinsic::x86_avx_vtestc_ps_256:
16660     case Intrinsic::x86_avx_vtestc_pd_256:
16661       IsTestPacked = true; // Fallthrough
16662     case Intrinsic::x86_sse41_ptestc:
16663     case Intrinsic::x86_avx_ptestc_256:
16664       // CF = 1
16665       X86CC = X86::COND_B;
16666       break;
16667     case Intrinsic::x86_avx_vtestnzc_ps:
16668     case Intrinsic::x86_avx_vtestnzc_pd:
16669     case Intrinsic::x86_avx_vtestnzc_ps_256:
16670     case Intrinsic::x86_avx_vtestnzc_pd_256:
16671       IsTestPacked = true; // Fallthrough
16672     case Intrinsic::x86_sse41_ptestnzc:
16673     case Intrinsic::x86_avx_ptestnzc_256:
16674       // ZF and CF = 0
16675       X86CC = X86::COND_A;
16676       break;
16677     }
16678
16679     SDValue LHS = Op.getOperand(1);
16680     SDValue RHS = Op.getOperand(2);
16681     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16682     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16683     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16684     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16685     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16686   }
16687   case Intrinsic::x86_avx512_kortestz_w:
16688   case Intrinsic::x86_avx512_kortestc_w: {
16689     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16690     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16691     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16692     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16693     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16694     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16695     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16696   }
16697
16698   case Intrinsic::x86_sse42_pcmpistria128:
16699   case Intrinsic::x86_sse42_pcmpestria128:
16700   case Intrinsic::x86_sse42_pcmpistric128:
16701   case Intrinsic::x86_sse42_pcmpestric128:
16702   case Intrinsic::x86_sse42_pcmpistrio128:
16703   case Intrinsic::x86_sse42_pcmpestrio128:
16704   case Intrinsic::x86_sse42_pcmpistris128:
16705   case Intrinsic::x86_sse42_pcmpestris128:
16706   case Intrinsic::x86_sse42_pcmpistriz128:
16707   case Intrinsic::x86_sse42_pcmpestriz128: {
16708     unsigned Opcode;
16709     unsigned X86CC;
16710     switch (IntNo) {
16711     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16712     case Intrinsic::x86_sse42_pcmpistria128:
16713       Opcode = X86ISD::PCMPISTRI;
16714       X86CC = X86::COND_A;
16715       break;
16716     case Intrinsic::x86_sse42_pcmpestria128:
16717       Opcode = X86ISD::PCMPESTRI;
16718       X86CC = X86::COND_A;
16719       break;
16720     case Intrinsic::x86_sse42_pcmpistric128:
16721       Opcode = X86ISD::PCMPISTRI;
16722       X86CC = X86::COND_B;
16723       break;
16724     case Intrinsic::x86_sse42_pcmpestric128:
16725       Opcode = X86ISD::PCMPESTRI;
16726       X86CC = X86::COND_B;
16727       break;
16728     case Intrinsic::x86_sse42_pcmpistrio128:
16729       Opcode = X86ISD::PCMPISTRI;
16730       X86CC = X86::COND_O;
16731       break;
16732     case Intrinsic::x86_sse42_pcmpestrio128:
16733       Opcode = X86ISD::PCMPESTRI;
16734       X86CC = X86::COND_O;
16735       break;
16736     case Intrinsic::x86_sse42_pcmpistris128:
16737       Opcode = X86ISD::PCMPISTRI;
16738       X86CC = X86::COND_S;
16739       break;
16740     case Intrinsic::x86_sse42_pcmpestris128:
16741       Opcode = X86ISD::PCMPESTRI;
16742       X86CC = X86::COND_S;
16743       break;
16744     case Intrinsic::x86_sse42_pcmpistriz128:
16745       Opcode = X86ISD::PCMPISTRI;
16746       X86CC = X86::COND_E;
16747       break;
16748     case Intrinsic::x86_sse42_pcmpestriz128:
16749       Opcode = X86ISD::PCMPESTRI;
16750       X86CC = X86::COND_E;
16751       break;
16752     }
16753     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16754     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16755     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16756     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16757                                 DAG.getConstant(X86CC, dl, MVT::i8),
16758                                 SDValue(PCMP.getNode(), 1));
16759     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16760   }
16761
16762   case Intrinsic::x86_sse42_pcmpistri128:
16763   case Intrinsic::x86_sse42_pcmpestri128: {
16764     unsigned Opcode;
16765     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16766       Opcode = X86ISD::PCMPISTRI;
16767     else
16768       Opcode = X86ISD::PCMPESTRI;
16769
16770     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16771     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16772     return DAG.getNode(Opcode, dl, VTs, NewOps);
16773   }
16774
16775   case Intrinsic::x86_seh_lsda: {
16776     // Compute the symbol for the LSDA. We know it'll get emitted later.
16777     MachineFunction &MF = DAG.getMachineFunction();
16778     SDValue Op1 = Op.getOperand(1);
16779     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16780     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16781         GlobalValue::getRealLinkageName(Fn->getName()));
16782
16783     // Generate a simple absolute symbol reference. This intrinsic is only
16784     // supported on 32-bit Windows, which isn't PIC.
16785     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16786     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16787   }
16788
16789   case Intrinsic::x86_seh_recoverfp: {
16790     SDValue FnOp = Op.getOperand(1);
16791     SDValue IncomingFPOp = Op.getOperand(2);
16792     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16793     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16794     if (!Fn)
16795       report_fatal_error(
16796           "llvm.x86.seh.recoverfp must take a function as the first argument");
16797     return recoverFramePointer(DAG, Fn, IncomingFPOp);
16798   }
16799
16800   case Intrinsic::localaddress: {
16801     // Returns one of the stack, base, or frame pointer registers, depending on
16802     // which is used to reference local variables.
16803     MachineFunction &MF = DAG.getMachineFunction();
16804     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16805     unsigned Reg;
16806     if (RegInfo->hasBasePointer(MF))
16807       Reg = RegInfo->getBaseRegister();
16808     else // This function handles the SP or FP case.
16809       Reg = RegInfo->getPtrSizedFrameRegister(MF);
16810     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16811   }
16812   }
16813 }
16814
16815 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16816                               SDValue Src, SDValue Mask, SDValue Base,
16817                               SDValue Index, SDValue ScaleOp, SDValue Chain,
16818                               const X86Subtarget * Subtarget) {
16819   SDLoc dl(Op);
16820   auto *C = cast<ConstantSDNode>(ScaleOp);
16821   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16822   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16823                              Index.getSimpleValueType().getVectorNumElements());
16824   SDValue MaskInReg;
16825   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16826   if (MaskC)
16827     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16828   else {
16829     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16830                                      Mask.getSimpleValueType().getSizeInBits());
16831
16832     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16833     // are extracted by EXTRACT_SUBVECTOR.
16834     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16835                             DAG.getBitcast(BitcastVT, Mask),
16836                             DAG.getIntPtrConstant(0, dl));
16837   }
16838   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16839   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16840   SDValue Segment = DAG.getRegister(0, MVT::i32);
16841   if (Src.getOpcode() == ISD::UNDEF)
16842     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16843   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16844   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16845   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16846   return DAG.getMergeValues(RetOps, dl);
16847 }
16848
16849 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16850                                SDValue Src, SDValue Mask, SDValue Base,
16851                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
16852   SDLoc dl(Op);
16853   auto *C = cast<ConstantSDNode>(ScaleOp);
16854   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16855   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16856   SDValue Segment = DAG.getRegister(0, MVT::i32);
16857   MVT MaskVT = MVT::getVectorVT(MVT::i1,
16858                              Index.getSimpleValueType().getVectorNumElements());
16859   SDValue MaskInReg;
16860   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16861   if (MaskC)
16862     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16863   else {
16864     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16865                                      Mask.getSimpleValueType().getSizeInBits());
16866
16867     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16868     // are extracted by EXTRACT_SUBVECTOR.
16869     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16870                             DAG.getBitcast(BitcastVT, Mask),
16871                             DAG.getIntPtrConstant(0, dl));
16872   }
16873   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16874   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16875   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16876   return SDValue(Res, 1);
16877 }
16878
16879 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16880                                SDValue Mask, SDValue Base, SDValue Index,
16881                                SDValue ScaleOp, SDValue Chain) {
16882   SDLoc dl(Op);
16883   auto *C = cast<ConstantSDNode>(ScaleOp);
16884   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16885   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16886   SDValue Segment = DAG.getRegister(0, MVT::i32);
16887   MVT MaskVT =
16888     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16889   SDValue MaskInReg;
16890   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16891   if (MaskC)
16892     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16893   else
16894     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16895   //SDVTList VTs = DAG.getVTList(MVT::Other);
16896   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16897   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16898   return SDValue(Res, 0);
16899 }
16900
16901 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16902 // read performance monitor counters (x86_rdpmc).
16903 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16904                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16905                               SmallVectorImpl<SDValue> &Results) {
16906   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16907   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16908   SDValue LO, HI;
16909
16910   // The ECX register is used to select the index of the performance counter
16911   // to read.
16912   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16913                                    N->getOperand(2));
16914   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16915
16916   // Reads the content of a 64-bit performance counter and returns it in the
16917   // registers EDX:EAX.
16918   if (Subtarget->is64Bit()) {
16919     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16920     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16921                             LO.getValue(2));
16922   } else {
16923     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16924     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16925                             LO.getValue(2));
16926   }
16927   Chain = HI.getValue(1);
16928
16929   if (Subtarget->is64Bit()) {
16930     // The EAX register is loaded with the low-order 32 bits. The EDX register
16931     // is loaded with the supported high-order bits of the counter.
16932     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16933                               DAG.getConstant(32, DL, MVT::i8));
16934     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16935     Results.push_back(Chain);
16936     return;
16937   }
16938
16939   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16940   SDValue Ops[] = { LO, HI };
16941   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16942   Results.push_back(Pair);
16943   Results.push_back(Chain);
16944 }
16945
16946 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16947 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16948 // also used to custom lower READCYCLECOUNTER nodes.
16949 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16950                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16951                               SmallVectorImpl<SDValue> &Results) {
16952   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16953   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16954   SDValue LO, HI;
16955
16956   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16957   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16958   // and the EAX register is loaded with the low-order 32 bits.
16959   if (Subtarget->is64Bit()) {
16960     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16961     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16962                             LO.getValue(2));
16963   } else {
16964     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16965     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16966                             LO.getValue(2));
16967   }
16968   SDValue Chain = HI.getValue(1);
16969
16970   if (Opcode == X86ISD::RDTSCP_DAG) {
16971     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16972
16973     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16974     // the ECX register. Add 'ecx' explicitly to the chain.
16975     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16976                                      HI.getValue(2));
16977     // Explicitly store the content of ECX at the location passed in input
16978     // to the 'rdtscp' intrinsic.
16979     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16980                          MachinePointerInfo(), false, false, 0);
16981   }
16982
16983   if (Subtarget->is64Bit()) {
16984     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16985     // the EAX register is loaded with the low-order 32 bits.
16986     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16987                               DAG.getConstant(32, DL, MVT::i8));
16988     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16989     Results.push_back(Chain);
16990     return;
16991   }
16992
16993   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16994   SDValue Ops[] = { LO, HI };
16995   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16996   Results.push_back(Pair);
16997   Results.push_back(Chain);
16998 }
16999
17000 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17001                                      SelectionDAG &DAG) {
17002   SmallVector<SDValue, 2> Results;
17003   SDLoc DL(Op);
17004   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17005                           Results);
17006   return DAG.getMergeValues(Results, DL);
17007 }
17008
17009 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
17010                                     SelectionDAG &DAG) {
17011   MachineFunction &MF = DAG.getMachineFunction();
17012   const Function *Fn = MF.getFunction();
17013   SDLoc dl(Op);
17014   SDValue Chain = Op.getOperand(0);
17015
17016   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
17017          "using llvm.x86.seh.restoreframe requires a frame pointer");
17018
17019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17020   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
17021
17022   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17023   unsigned FrameReg =
17024       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17025   unsigned SPReg = RegInfo->getStackRegister();
17026   unsigned SlotSize = RegInfo->getSlotSize();
17027
17028   // Get incoming EBP.
17029   SDValue IncomingEBP =
17030       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
17031
17032   // SP is saved in the first field of every registration node, so load
17033   // [EBP-RegNodeSize] into SP.
17034   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
17035   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
17036                                DAG.getConstant(-RegNodeSize, dl, VT));
17037   SDValue NewSP =
17038       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
17039                   false, VT.getScalarSizeInBits() / 8);
17040   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
17041
17042   if (!RegInfo->needsStackRealignment(MF)) {
17043     // Adjust EBP to point back to the original frame position.
17044     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
17045     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
17046   } else {
17047     assert(RegInfo->hasBasePointer(MF) &&
17048            "functions with Win32 EH must use frame or base pointer register");
17049
17050     // Reload the base pointer (ESI) with the adjusted incoming EBP.
17051     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
17052     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
17053
17054     // Reload the spilled EBP value, now that the stack and base pointers are
17055     // set up.
17056     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
17057     X86FI->setHasSEHFramePtrSave(true);
17058     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
17059     X86FI->setSEHFramePtrSaveIndex(FI);
17060     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
17061                                 MachinePointerInfo(), false, false, false,
17062                                 VT.getScalarSizeInBits() / 8);
17063     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
17064   }
17065
17066   return Chain;
17067 }
17068
17069 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17070   MachineFunction &MF = DAG.getMachineFunction();
17071   SDValue Chain = Op.getOperand(0);
17072   SDValue RegNode = Op.getOperand(2);
17073   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17074   if (!EHInfo)
17075     report_fatal_error("EH registrations only live in functions using WinEH");
17076
17077   // Cast the operand to an alloca, and remember the frame index.
17078   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17079   if (!FINode)
17080     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17081   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17082
17083   // Return the chain operand without making any DAG nodes.
17084   return Chain;
17085 }
17086
17087 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17088 /// return truncate Store/MaskedStore Node
17089 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17090                                                SelectionDAG &DAG,
17091                                                MVT ElementType) {
17092   SDLoc dl(Op);
17093   SDValue Mask = Op.getOperand(4);
17094   SDValue DataToTruncate = Op.getOperand(3);
17095   SDValue Addr = Op.getOperand(2);
17096   SDValue Chain = Op.getOperand(0);
17097
17098   MVT VT  = DataToTruncate.getSimpleValueType();
17099   MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17100
17101   if (isAllOnes(Mask)) // return just a truncate store
17102     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17103                              MachinePointerInfo(), SVT, false, false,
17104                              SVT.getScalarSizeInBits()/8);
17105
17106   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17107   MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17108                                    Mask.getSimpleValueType().getSizeInBits());
17109   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17110   // are extracted by EXTRACT_SUBVECTOR.
17111   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17112                               DAG.getBitcast(BitcastVT, Mask),
17113                               DAG.getIntPtrConstant(0, dl));
17114
17115   MachineMemOperand *MMO = DAG.getMachineFunction().
17116     getMachineMemOperand(MachinePointerInfo(),
17117                          MachineMemOperand::MOStore, SVT.getStoreSize(),
17118                          SVT.getScalarSizeInBits()/8);
17119
17120   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17121                             VMask, SVT, MMO, true);
17122 }
17123
17124 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17125                                       SelectionDAG &DAG) {
17126   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17127
17128   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17129   if (!IntrData) {
17130     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
17131       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
17132     else if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17133       return MarkEHRegistrationNode(Op, DAG);
17134     return SDValue();
17135   }
17136
17137   SDLoc dl(Op);
17138   switch(IntrData->Type) {
17139   default: llvm_unreachable("Unknown Intrinsic Type");
17140   case RDSEED:
17141   case RDRAND: {
17142     // Emit the node with the right value type.
17143     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17144     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17145
17146     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17147     // Otherwise return the value from Rand, which is always 0, casted to i32.
17148     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17149                       DAG.getConstant(1, dl, Op->getValueType(1)),
17150                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
17151                       SDValue(Result.getNode(), 1) };
17152     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17153                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
17154                                   Ops);
17155
17156     // Return { result, isValid, chain }.
17157     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17158                        SDValue(Result.getNode(), 2));
17159   }
17160   case GATHER: {
17161   //gather(v1, mask, index, base, scale);
17162     SDValue Chain = Op.getOperand(0);
17163     SDValue Src   = Op.getOperand(2);
17164     SDValue Base  = Op.getOperand(3);
17165     SDValue Index = Op.getOperand(4);
17166     SDValue Mask  = Op.getOperand(5);
17167     SDValue Scale = Op.getOperand(6);
17168     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17169                          Chain, Subtarget);
17170   }
17171   case SCATTER: {
17172   //scatter(base, mask, index, v1, scale);
17173     SDValue Chain = Op.getOperand(0);
17174     SDValue Base  = Op.getOperand(2);
17175     SDValue Mask  = Op.getOperand(3);
17176     SDValue Index = Op.getOperand(4);
17177     SDValue Src   = Op.getOperand(5);
17178     SDValue Scale = Op.getOperand(6);
17179     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17180                           Scale, Chain);
17181   }
17182   case PREFETCH: {
17183     SDValue Hint = Op.getOperand(6);
17184     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17185     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17186     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17187     SDValue Chain = Op.getOperand(0);
17188     SDValue Mask  = Op.getOperand(2);
17189     SDValue Index = Op.getOperand(3);
17190     SDValue Base  = Op.getOperand(4);
17191     SDValue Scale = Op.getOperand(5);
17192     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17193   }
17194   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17195   case RDTSC: {
17196     SmallVector<SDValue, 2> Results;
17197     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17198                             Results);
17199     return DAG.getMergeValues(Results, dl);
17200   }
17201   // Read Performance Monitoring Counters.
17202   case RDPMC: {
17203     SmallVector<SDValue, 2> Results;
17204     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17205     return DAG.getMergeValues(Results, dl);
17206   }
17207   // XTEST intrinsics.
17208   case XTEST: {
17209     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17210     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17211     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17212                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17213                                 InTrans);
17214     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17215     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17216                        Ret, SDValue(InTrans.getNode(), 1));
17217   }
17218   // ADC/ADCX/SBB
17219   case ADX: {
17220     SmallVector<SDValue, 2> Results;
17221     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17222     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17223     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17224                                 DAG.getConstant(-1, dl, MVT::i8));
17225     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17226                               Op.getOperand(4), GenCF.getValue(1));
17227     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17228                                  Op.getOperand(5), MachinePointerInfo(),
17229                                  false, false, 0);
17230     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17231                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17232                                 Res.getValue(1));
17233     Results.push_back(SetCC);
17234     Results.push_back(Store);
17235     return DAG.getMergeValues(Results, dl);
17236   }
17237   case COMPRESS_TO_MEM: {
17238     SDLoc dl(Op);
17239     SDValue Mask = Op.getOperand(4);
17240     SDValue DataToCompress = Op.getOperand(3);
17241     SDValue Addr = Op.getOperand(2);
17242     SDValue Chain = Op.getOperand(0);
17243
17244     MVT VT = DataToCompress.getSimpleValueType();
17245     if (isAllOnes(Mask)) // return just a store
17246       return DAG.getStore(Chain, dl, DataToCompress, Addr,
17247                           MachinePointerInfo(), false, false,
17248                           VT.getScalarSizeInBits()/8);
17249
17250     SDValue Compressed =
17251       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17252                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17253     return DAG.getStore(Chain, dl, Compressed, Addr,
17254                         MachinePointerInfo(), false, false,
17255                         VT.getScalarSizeInBits()/8);
17256   }
17257   case TRUNCATE_TO_MEM_VI8:
17258     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17259   case TRUNCATE_TO_MEM_VI16:
17260     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17261   case TRUNCATE_TO_MEM_VI32:
17262     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17263   case EXPAND_FROM_MEM: {
17264     SDLoc dl(Op);
17265     SDValue Mask = Op.getOperand(4);
17266     SDValue PassThru = Op.getOperand(3);
17267     SDValue Addr = Op.getOperand(2);
17268     SDValue Chain = Op.getOperand(0);
17269     MVT VT = Op.getSimpleValueType();
17270
17271     if (isAllOnes(Mask)) // return just a load
17272       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17273                          false, VT.getScalarSizeInBits()/8);
17274
17275     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17276                                        false, false, false,
17277                                        VT.getScalarSizeInBits()/8);
17278
17279     SDValue Results[] = {
17280       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17281                            Mask, PassThru, Subtarget, DAG), Chain};
17282     return DAG.getMergeValues(Results, dl);
17283   }
17284   }
17285 }
17286
17287 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17288                                            SelectionDAG &DAG) const {
17289   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17290   MFI->setReturnAddressIsTaken(true);
17291
17292   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17293     return SDValue();
17294
17295   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17296   SDLoc dl(Op);
17297   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17298
17299   if (Depth > 0) {
17300     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17301     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17302     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17303     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17304                        DAG.getNode(ISD::ADD, dl, PtrVT,
17305                                    FrameAddr, Offset),
17306                        MachinePointerInfo(), false, false, false, 0);
17307   }
17308
17309   // Just load the return address.
17310   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17311   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17312                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17313 }
17314
17315 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17316   MachineFunction &MF = DAG.getMachineFunction();
17317   MachineFrameInfo *MFI = MF.getFrameInfo();
17318   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17319   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17320   EVT VT = Op.getValueType();
17321
17322   MFI->setFrameAddressIsTaken(true);
17323
17324   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17325     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
17326     // is not possible to crawl up the stack without looking at the unwind codes
17327     // simultaneously.
17328     int FrameAddrIndex = FuncInfo->getFAIndex();
17329     if (!FrameAddrIndex) {
17330       // Set up a frame object for the return address.
17331       unsigned SlotSize = RegInfo->getSlotSize();
17332       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17333           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17334       FuncInfo->setFAIndex(FrameAddrIndex);
17335     }
17336     return DAG.getFrameIndex(FrameAddrIndex, VT);
17337   }
17338
17339   unsigned FrameReg =
17340       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17341   SDLoc dl(Op);  // FIXME probably not meaningful
17342   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17343   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17344           (FrameReg == X86::EBP && VT == MVT::i32)) &&
17345          "Invalid Frame Register!");
17346   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17347   while (Depth--)
17348     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17349                             MachinePointerInfo(),
17350                             false, false, false, 0);
17351   return FrameAddr;
17352 }
17353
17354 // FIXME? Maybe this could be a TableGen attribute on some registers and
17355 // this table could be generated automatically from RegInfo.
17356 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17357                                               SelectionDAG &DAG) const {
17358   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17359   const MachineFunction &MF = DAG.getMachineFunction();
17360
17361   unsigned Reg = StringSwitch<unsigned>(RegName)
17362                        .Case("esp", X86::ESP)
17363                        .Case("rsp", X86::RSP)
17364                        .Case("ebp", X86::EBP)
17365                        .Case("rbp", X86::RBP)
17366                        .Default(0);
17367
17368   if (Reg == X86::EBP || Reg == X86::RBP) {
17369     if (!TFI.hasFP(MF))
17370       report_fatal_error("register " + StringRef(RegName) +
17371                          " is allocatable: function has no frame pointer");
17372 #ifndef NDEBUG
17373     else {
17374       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17375       unsigned FrameReg =
17376           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17377       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17378              "Invalid Frame Register!");
17379     }
17380 #endif
17381   }
17382
17383   if (Reg)
17384     return Reg;
17385
17386   report_fatal_error("Invalid register name global variable");
17387 }
17388
17389 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17390                                                      SelectionDAG &DAG) const {
17391   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17392   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17393 }
17394
17395 unsigned X86TargetLowering::getExceptionPointerRegister(
17396     const Constant *PersonalityFn) const {
17397   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17398     return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17399
17400   return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17401 }
17402
17403 unsigned X86TargetLowering::getExceptionSelectorRegister(
17404     const Constant *PersonalityFn) const {
17405   // Funclet personalities don't use selectors (the runtime does the selection).
17406   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17407   return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17408 }
17409
17410 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17411   SDValue Chain     = Op.getOperand(0);
17412   SDValue Offset    = Op.getOperand(1);
17413   SDValue Handler   = Op.getOperand(2);
17414   SDLoc dl      (Op);
17415
17416   EVT PtrVT = getPointerTy(DAG.getDataLayout());
17417   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17418   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17419   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17420           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17421          "Invalid Frame Register!");
17422   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17423   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17424
17425   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17426                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17427                                                        dl));
17428   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17429   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17430                        false, false, 0);
17431   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17432
17433   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17434                      DAG.getRegister(StoreAddrReg, PtrVT));
17435 }
17436
17437 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17438                                                SelectionDAG &DAG) const {
17439   SDLoc DL(Op);
17440   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17441                      DAG.getVTList(MVT::i32, MVT::Other),
17442                      Op.getOperand(0), Op.getOperand(1));
17443 }
17444
17445 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17446                                                 SelectionDAG &DAG) const {
17447   SDLoc DL(Op);
17448   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17449                      Op.getOperand(0), Op.getOperand(1));
17450 }
17451
17452 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17453   return Op.getOperand(0);
17454 }
17455
17456 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17457                                                 SelectionDAG &DAG) const {
17458   SDValue Root = Op.getOperand(0);
17459   SDValue Trmp = Op.getOperand(1); // trampoline
17460   SDValue FPtr = Op.getOperand(2); // nested function
17461   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17462   SDLoc dl (Op);
17463
17464   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17465   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17466
17467   if (Subtarget->is64Bit()) {
17468     SDValue OutChains[6];
17469
17470     // Large code-model.
17471     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
17472     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17473
17474     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17475     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17476
17477     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17478
17479     // Load the pointer to the nested function into R11.
17480     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17481     SDValue Addr = Trmp;
17482     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17483                                 Addr, MachinePointerInfo(TrmpAddr),
17484                                 false, false, 0);
17485
17486     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17487                        DAG.getConstant(2, dl, MVT::i64));
17488     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17489                                 MachinePointerInfo(TrmpAddr, 2),
17490                                 false, false, 2);
17491
17492     // Load the 'nest' parameter value into R10.
17493     // R10 is specified in X86CallingConv.td
17494     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17495     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17496                        DAG.getConstant(10, dl, MVT::i64));
17497     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17498                                 Addr, MachinePointerInfo(TrmpAddr, 10),
17499                                 false, false, 0);
17500
17501     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17502                        DAG.getConstant(12, dl, MVT::i64));
17503     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17504                                 MachinePointerInfo(TrmpAddr, 12),
17505                                 false, false, 2);
17506
17507     // Jump to the nested function.
17508     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17509     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17510                        DAG.getConstant(20, dl, MVT::i64));
17511     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17512                                 Addr, MachinePointerInfo(TrmpAddr, 20),
17513                                 false, false, 0);
17514
17515     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17516     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17517                        DAG.getConstant(22, dl, MVT::i64));
17518     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17519                                 Addr, MachinePointerInfo(TrmpAddr, 22),
17520                                 false, false, 0);
17521
17522     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17523   } else {
17524     const Function *Func =
17525       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17526     CallingConv::ID CC = Func->getCallingConv();
17527     unsigned NestReg;
17528
17529     switch (CC) {
17530     default:
17531       llvm_unreachable("Unsupported calling convention");
17532     case CallingConv::C:
17533     case CallingConv::X86_StdCall: {
17534       // Pass 'nest' parameter in ECX.
17535       // Must be kept in sync with X86CallingConv.td
17536       NestReg = X86::ECX;
17537
17538       // Check that ECX wasn't needed by an 'inreg' parameter.
17539       FunctionType *FTy = Func->getFunctionType();
17540       const AttributeSet &Attrs = Func->getAttributes();
17541
17542       if (!Attrs.isEmpty() && !Func->isVarArg()) {
17543         unsigned InRegCount = 0;
17544         unsigned Idx = 1;
17545
17546         for (FunctionType::param_iterator I = FTy->param_begin(),
17547              E = FTy->param_end(); I != E; ++I, ++Idx)
17548           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17549             auto &DL = DAG.getDataLayout();
17550             // FIXME: should only count parameters that are lowered to integers.
17551             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17552           }
17553
17554         if (InRegCount > 2) {
17555           report_fatal_error("Nest register in use - reduce number of inreg"
17556                              " parameters!");
17557         }
17558       }
17559       break;
17560     }
17561     case CallingConv::X86_FastCall:
17562     case CallingConv::X86_ThisCall:
17563     case CallingConv::Fast:
17564       // Pass 'nest' parameter in EAX.
17565       // Must be kept in sync with X86CallingConv.td
17566       NestReg = X86::EAX;
17567       break;
17568     }
17569
17570     SDValue OutChains[4];
17571     SDValue Addr, Disp;
17572
17573     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17574                        DAG.getConstant(10, dl, MVT::i32));
17575     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17576
17577     // This is storing the opcode for MOV32ri.
17578     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17579     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17580     OutChains[0] = DAG.getStore(Root, dl,
17581                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17582                                 Trmp, MachinePointerInfo(TrmpAddr),
17583                                 false, false, 0);
17584
17585     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17586                        DAG.getConstant(1, dl, MVT::i32));
17587     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17588                                 MachinePointerInfo(TrmpAddr, 1),
17589                                 false, false, 1);
17590
17591     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17592     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17593                        DAG.getConstant(5, dl, MVT::i32));
17594     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17595                                 Addr, MachinePointerInfo(TrmpAddr, 5),
17596                                 false, false, 1);
17597
17598     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17599                        DAG.getConstant(6, dl, MVT::i32));
17600     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17601                                 MachinePointerInfo(TrmpAddr, 6),
17602                                 false, false, 1);
17603
17604     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17605   }
17606 }
17607
17608 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17609                                             SelectionDAG &DAG) const {
17610   /*
17611    The rounding mode is in bits 11:10 of FPSR, and has the following
17612    settings:
17613      00 Round to nearest
17614      01 Round to -inf
17615      10 Round to +inf
17616      11 Round to 0
17617
17618   FLT_ROUNDS, on the other hand, expects the following:
17619     -1 Undefined
17620      0 Round to 0
17621      1 Round to nearest
17622      2 Round to +inf
17623      3 Round to -inf
17624
17625   To perform the conversion, we do:
17626     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17627   */
17628
17629   MachineFunction &MF = DAG.getMachineFunction();
17630   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17631   unsigned StackAlignment = TFI.getStackAlignment();
17632   MVT VT = Op.getSimpleValueType();
17633   SDLoc DL(Op);
17634
17635   // Save FP Control Word to stack slot
17636   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17637   SDValue StackSlot =
17638       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17639
17640   MachineMemOperand *MMO =
17641       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17642                               MachineMemOperand::MOStore, 2, 2);
17643
17644   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17645   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17646                                           DAG.getVTList(MVT::Other),
17647                                           Ops, MVT::i16, MMO);
17648
17649   // Load FP Control Word from stack slot
17650   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17651                             MachinePointerInfo(), false, false, false, 0);
17652
17653   // Transform as necessary
17654   SDValue CWD1 =
17655     DAG.getNode(ISD::SRL, DL, MVT::i16,
17656                 DAG.getNode(ISD::AND, DL, MVT::i16,
17657                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17658                 DAG.getConstant(11, DL, MVT::i8));
17659   SDValue CWD2 =
17660     DAG.getNode(ISD::SRL, DL, MVT::i16,
17661                 DAG.getNode(ISD::AND, DL, MVT::i16,
17662                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17663                 DAG.getConstant(9, DL, MVT::i8));
17664
17665   SDValue RetVal =
17666     DAG.getNode(ISD::AND, DL, MVT::i16,
17667                 DAG.getNode(ISD::ADD, DL, MVT::i16,
17668                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17669                             DAG.getConstant(1, DL, MVT::i16)),
17670                 DAG.getConstant(3, DL, MVT::i16));
17671
17672   return DAG.getNode((VT.getSizeInBits() < 16 ?
17673                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17674 }
17675
17676 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17677 //
17678 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17679 //    to 512-bit vector.
17680 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17681 //    ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17682 //    split the vector, perform operation on it's Lo a Hi part and
17683 //    concatenate the results.
17684 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17685   SDLoc dl(Op);
17686   MVT VT = Op.getSimpleValueType();
17687   MVT EltVT = VT.getVectorElementType();
17688   unsigned NumElems = VT.getVectorNumElements();
17689
17690   if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17691     // Extend to 512 bit vector.
17692     assert((VT.is256BitVector() || VT.is128BitVector()) &&
17693               "Unsupported value type for operation");
17694
17695     MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17696     SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17697                                  DAG.getUNDEF(NewVT),
17698                                  Op.getOperand(0),
17699                                  DAG.getIntPtrConstant(0, dl));
17700     SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17701
17702     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17703                        DAG.getIntPtrConstant(0, dl));
17704   }
17705
17706   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17707           "Unsupported element type");
17708
17709   if (16 < NumElems) {
17710     // Split vector, it's Lo and Hi parts will be handled in next iteration.
17711     SDValue Lo, Hi;
17712     std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17713     MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17714
17715     Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17716     Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17717
17718     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17719   }
17720
17721   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17722
17723   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17724           "Unsupported value type for operation");
17725
17726   // Use native supported vector instruction vplzcntd.
17727   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17728   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17729   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17730   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17731
17732   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17733 }
17734
17735 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17736                          SelectionDAG &DAG) {
17737   MVT VT = Op.getSimpleValueType();
17738   MVT OpVT = VT;
17739   unsigned NumBits = VT.getSizeInBits();
17740   SDLoc dl(Op);
17741
17742   if (VT.isVector() && Subtarget->hasAVX512())
17743     return LowerVectorCTLZ_AVX512(Op, DAG);
17744
17745   Op = Op.getOperand(0);
17746   if (VT == MVT::i8) {
17747     // Zero extend to i32 since there is not an i8 bsr.
17748     OpVT = MVT::i32;
17749     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17750   }
17751
17752   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17753   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17754   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17755
17756   // If src is zero (i.e. bsr sets ZF), returns NumBits.
17757   SDValue Ops[] = {
17758     Op,
17759     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17760     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17761     Op.getValue(1)
17762   };
17763   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17764
17765   // Finally xor with NumBits-1.
17766   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17767                    DAG.getConstant(NumBits - 1, dl, OpVT));
17768
17769   if (VT == MVT::i8)
17770     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17771   return Op;
17772 }
17773
17774 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17775                                     SelectionDAG &DAG) {
17776   MVT VT = Op.getSimpleValueType();
17777   EVT OpVT = VT;
17778   unsigned NumBits = VT.getSizeInBits();
17779   SDLoc dl(Op);
17780
17781   if (VT.isVector() && Subtarget->hasAVX512())
17782     return LowerVectorCTLZ_AVX512(Op, DAG);
17783
17784   Op = Op.getOperand(0);
17785   if (VT == MVT::i8) {
17786     // Zero extend to i32 since there is not an i8 bsr.
17787     OpVT = MVT::i32;
17788     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17789   }
17790
17791   // Issue a bsr (scan bits in reverse).
17792   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17793   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17794
17795   // And xor with NumBits-1.
17796   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17797                    DAG.getConstant(NumBits - 1, dl, OpVT));
17798
17799   if (VT == MVT::i8)
17800     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17801   return Op;
17802 }
17803
17804 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17805   MVT VT = Op.getSimpleValueType();
17806   unsigned NumBits = VT.getScalarSizeInBits();
17807   SDLoc dl(Op);
17808
17809   if (VT.isVector()) {
17810     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17811
17812     SDValue N0 = Op.getOperand(0);
17813     SDValue Zero = DAG.getConstant(0, dl, VT);
17814
17815     // lsb(x) = (x & -x)
17816     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17817                               DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17818
17819     // cttz_undef(x) = (width - 1) - ctlz(lsb)
17820     if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17821         TLI.isOperationLegal(ISD::CTLZ, VT)) {
17822       SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17823       return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17824                          DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17825     }
17826
17827     // cttz(x) = ctpop(lsb - 1)
17828     SDValue One = DAG.getConstant(1, dl, VT);
17829     return DAG.getNode(ISD::CTPOP, dl, VT,
17830                        DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17831   }
17832
17833   assert(Op.getOpcode() == ISD::CTTZ &&
17834          "Only scalar CTTZ requires custom lowering");
17835
17836   // Issue a bsf (scan bits forward) which also sets EFLAGS.
17837   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17838   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17839
17840   // If src is zero (i.e. bsf sets ZF), returns NumBits.
17841   SDValue Ops[] = {
17842     Op,
17843     DAG.getConstant(NumBits, dl, VT),
17844     DAG.getConstant(X86::COND_E, dl, MVT::i8),
17845     Op.getValue(1)
17846   };
17847   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17848 }
17849
17850 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17851 // ones, and then concatenate the result back.
17852 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17853   MVT VT = Op.getSimpleValueType();
17854
17855   assert(VT.is256BitVector() && VT.isInteger() &&
17856          "Unsupported value type for operation");
17857
17858   unsigned NumElems = VT.getVectorNumElements();
17859   SDLoc dl(Op);
17860
17861   // Extract the LHS vectors
17862   SDValue LHS = Op.getOperand(0);
17863   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17864   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17865
17866   // Extract the RHS vectors
17867   SDValue RHS = Op.getOperand(1);
17868   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17869   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17870
17871   MVT EltVT = VT.getVectorElementType();
17872   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17873
17874   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17875                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17876                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17877 }
17878
17879 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17880   if (Op.getValueType() == MVT::i1)
17881     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17882                        Op.getOperand(0), Op.getOperand(1));
17883   assert(Op.getSimpleValueType().is256BitVector() &&
17884          Op.getSimpleValueType().isInteger() &&
17885          "Only handle AVX 256-bit vector integer operation");
17886   return Lower256IntArith(Op, DAG);
17887 }
17888
17889 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17890   if (Op.getValueType() == MVT::i1)
17891     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17892                        Op.getOperand(0), Op.getOperand(1));
17893   assert(Op.getSimpleValueType().is256BitVector() &&
17894          Op.getSimpleValueType().isInteger() &&
17895          "Only handle AVX 256-bit vector integer operation");
17896   return Lower256IntArith(Op, DAG);
17897 }
17898
17899 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17900   assert(Op.getSimpleValueType().is256BitVector() &&
17901          Op.getSimpleValueType().isInteger() &&
17902          "Only handle AVX 256-bit vector integer operation");
17903   return Lower256IntArith(Op, DAG);
17904 }
17905
17906 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17907                         SelectionDAG &DAG) {
17908   SDLoc dl(Op);
17909   MVT VT = Op.getSimpleValueType();
17910
17911   if (VT == MVT::i1)
17912     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17913
17914   // Decompose 256-bit ops into smaller 128-bit ops.
17915   if (VT.is256BitVector() && !Subtarget->hasInt256())
17916     return Lower256IntArith(Op, DAG);
17917
17918   SDValue A = Op.getOperand(0);
17919   SDValue B = Op.getOperand(1);
17920
17921   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17922   // pairs, multiply and truncate.
17923   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17924     if (Subtarget->hasInt256()) {
17925       if (VT == MVT::v32i8) {
17926         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17927         SDValue Lo = DAG.getIntPtrConstant(0, dl);
17928         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17929         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17930         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17931         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17932         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17933         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17934                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17935                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17936       }
17937
17938       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17939       return DAG.getNode(
17940           ISD::TRUNCATE, dl, VT,
17941           DAG.getNode(ISD::MUL, dl, ExVT,
17942                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17943                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17944     }
17945
17946     assert(VT == MVT::v16i8 &&
17947            "Pre-AVX2 support only supports v16i8 multiplication");
17948     MVT ExVT = MVT::v8i16;
17949
17950     // Extract the lo parts and sign extend to i16
17951     SDValue ALo, BLo;
17952     if (Subtarget->hasSSE41()) {
17953       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17954       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17955     } else {
17956       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17957                               -1, 4, -1, 5, -1, 6, -1, 7};
17958       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17959       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17960       ALo = DAG.getBitcast(ExVT, ALo);
17961       BLo = DAG.getBitcast(ExVT, BLo);
17962       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17963       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17964     }
17965
17966     // Extract the hi parts and sign extend to i16
17967     SDValue AHi, BHi;
17968     if (Subtarget->hasSSE41()) {
17969       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
17970                               -1, -1, -1, -1, -1, -1, -1, -1};
17971       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17972       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17973       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17974       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17975     } else {
17976       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
17977                               -1, 12, -1, 13, -1, 14, -1, 15};
17978       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17979       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17980       AHi = DAG.getBitcast(ExVT, AHi);
17981       BHi = DAG.getBitcast(ExVT, BHi);
17982       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17983       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17984     }
17985
17986     // Multiply, mask the lower 8bits of the lo/hi results and pack
17987     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17988     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17989     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17990     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17991     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17992   }
17993
17994   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17995   if (VT == MVT::v4i32) {
17996     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17997            "Should not custom lower when pmuldq is available!");
17998
17999     // Extract the odd parts.
18000     static const int UnpackMask[] = { 1, -1, 3, -1 };
18001     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18002     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18003
18004     // Multiply the even parts.
18005     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18006     // Now multiply odd parts.
18007     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18008
18009     Evens = DAG.getBitcast(VT, Evens);
18010     Odds = DAG.getBitcast(VT, Odds);
18011
18012     // Merge the two vectors back together with a shuffle. This expands into 2
18013     // shuffles.
18014     static const int ShufMask[] = { 0, 4, 2, 6 };
18015     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18016   }
18017
18018   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18019          "Only know how to lower V2I64/V4I64/V8I64 multiply");
18020
18021   //  Ahi = psrlqi(a, 32);
18022   //  Bhi = psrlqi(b, 32);
18023   //
18024   //  AloBlo = pmuludq(a, b);
18025   //  AloBhi = pmuludq(a, Bhi);
18026   //  AhiBlo = pmuludq(Ahi, b);
18027
18028   //  AloBhi = psllqi(AloBhi, 32);
18029   //  AhiBlo = psllqi(AhiBlo, 32);
18030   //  return AloBlo + AloBhi + AhiBlo;
18031
18032   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18033   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18034
18035   SDValue AhiBlo = Ahi;
18036   SDValue AloBhi = Bhi;
18037   // Bit cast to 32-bit vectors for MULUDQ
18038   MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18039                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18040   A = DAG.getBitcast(MulVT, A);
18041   B = DAG.getBitcast(MulVT, B);
18042   Ahi = DAG.getBitcast(MulVT, Ahi);
18043   Bhi = DAG.getBitcast(MulVT, Bhi);
18044
18045   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18046   // After shifting right const values the result may be all-zero.
18047   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18048     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18049     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18050   }
18051   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18052     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18053     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18054   }
18055
18056   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18057   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18058 }
18059
18060 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18061   assert(Subtarget->isTargetWin64() && "Unexpected target");
18062   EVT VT = Op.getValueType();
18063   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18064          "Unexpected return type for lowering");
18065
18066   RTLIB::Libcall LC;
18067   bool isSigned;
18068   switch (Op->getOpcode()) {
18069   default: llvm_unreachable("Unexpected request for libcall!");
18070   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
18071   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
18072   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
18073   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
18074   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
18075   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18076   }
18077
18078   SDLoc dl(Op);
18079   SDValue InChain = DAG.getEntryNode();
18080
18081   TargetLowering::ArgListTy Args;
18082   TargetLowering::ArgListEntry Entry;
18083   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18084     EVT ArgVT = Op->getOperand(i).getValueType();
18085     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18086            "Unexpected argument type for lowering");
18087     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18088     Entry.Node = StackPtr;
18089     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18090                            false, false, 16);
18091     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18092     Entry.Ty = PointerType::get(ArgTy,0);
18093     Entry.isSExt = false;
18094     Entry.isZExt = false;
18095     Args.push_back(Entry);
18096   }
18097
18098   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18099                                          getPointerTy(DAG.getDataLayout()));
18100
18101   TargetLowering::CallLoweringInfo CLI(DAG);
18102   CLI.setDebugLoc(dl).setChain(InChain)
18103     .setCallee(getLibcallCallingConv(LC),
18104                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18105                Callee, std::move(Args), 0)
18106     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18107
18108   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18109   return DAG.getBitcast(VT, CallInfo.first);
18110 }
18111
18112 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18113                              SelectionDAG &DAG) {
18114   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18115   MVT VT = Op0.getSimpleValueType();
18116   SDLoc dl(Op);
18117
18118   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18119          (VT == MVT::v8i32 && Subtarget->hasInt256()));
18120
18121   // PMULxD operations multiply each even value (starting at 0) of LHS with
18122   // the related value of RHS and produce a widen result.
18123   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18124   // => <2 x i64> <ae|cg>
18125   //
18126   // In other word, to have all the results, we need to perform two PMULxD:
18127   // 1. one with the even values.
18128   // 2. one with the odd values.
18129   // To achieve #2, with need to place the odd values at an even position.
18130   //
18131   // Place the odd value at an even position (basically, shift all values 1
18132   // step to the left):
18133   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18134   // <a|b|c|d> => <b|undef|d|undef>
18135   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18136   // <e|f|g|h> => <f|undef|h|undef>
18137   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18138
18139   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18140   // ints.
18141   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18142   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18143   unsigned Opcode =
18144       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18145   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18146   // => <2 x i64> <ae|cg>
18147   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18148   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18149   // => <2 x i64> <bf|dh>
18150   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18151
18152   // Shuffle it back into the right order.
18153   SDValue Highs, Lows;
18154   if (VT == MVT::v8i32) {
18155     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18156     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18157     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18158     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18159   } else {
18160     const int HighMask[] = {1, 5, 3, 7};
18161     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18162     const int LowMask[] = {0, 4, 2, 6};
18163     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18164   }
18165
18166   // If we have a signed multiply but no PMULDQ fix up the high parts of a
18167   // unsigned multiply.
18168   if (IsSigned && !Subtarget->hasSSE41()) {
18169     SDValue ShAmt = DAG.getConstant(
18170         31, dl,
18171         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18172     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18173                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18174     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18175                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18176
18177     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18178     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18179   }
18180
18181   // The first result of MUL_LOHI is actually the low value, followed by the
18182   // high value.
18183   SDValue Ops[] = {Lows, Highs};
18184   return DAG.getMergeValues(Ops, dl);
18185 }
18186
18187 // Return true if the required (according to Opcode) shift-imm form is natively
18188 // supported by the Subtarget
18189 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18190                                         unsigned Opcode) {
18191   if (VT.getScalarSizeInBits() < 16)
18192     return false;
18193
18194   if (VT.is512BitVector() &&
18195       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18196     return true;
18197
18198   bool LShift = VT.is128BitVector() ||
18199     (VT.is256BitVector() && Subtarget->hasInt256());
18200
18201   bool AShift = LShift && (Subtarget->hasVLX() ||
18202     (VT != MVT::v2i64 && VT != MVT::v4i64));
18203   return (Opcode == ISD::SRA) ? AShift : LShift;
18204 }
18205
18206 // The shift amount is a variable, but it is the same for all vector lanes.
18207 // These instructions are defined together with shift-immediate.
18208 static
18209 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18210                                       unsigned Opcode) {
18211   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18212 }
18213
18214 // Return true if the required (according to Opcode) variable-shift form is
18215 // natively supported by the Subtarget
18216 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18217                                     unsigned Opcode) {
18218
18219   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18220     return false;
18221
18222   // vXi16 supported only on AVX-512, BWI
18223   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18224     return false;
18225
18226   if (VT.is512BitVector() || Subtarget->hasVLX())
18227     return true;
18228
18229   bool LShift = VT.is128BitVector() || VT.is256BitVector();
18230   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
18231   return (Opcode == ISD::SRA) ? AShift : LShift;
18232 }
18233
18234 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18235                                          const X86Subtarget *Subtarget) {
18236   MVT VT = Op.getSimpleValueType();
18237   SDLoc dl(Op);
18238   SDValue R = Op.getOperand(0);
18239   SDValue Amt = Op.getOperand(1);
18240
18241   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18242     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18243
18244   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18245     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18246     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18247     SDValue Ex = DAG.getBitcast(ExVT, R);
18248
18249     if (ShiftAmt >= 32) {
18250       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18251       SDValue Upper =
18252           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18253       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18254                                                  ShiftAmt - 32, DAG);
18255       if (VT == MVT::v2i64)
18256         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18257       if (VT == MVT::v4i64)
18258         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18259                                   {9, 1, 11, 3, 13, 5, 15, 7});
18260     } else {
18261       // SRA upper i32, SHL whole i64 and select lower i32.
18262       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18263                                                  ShiftAmt, DAG);
18264       SDValue Lower =
18265           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18266       Lower = DAG.getBitcast(ExVT, Lower);
18267       if (VT == MVT::v2i64)
18268         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18269       if (VT == MVT::v4i64)
18270         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18271                                   {8, 1, 10, 3, 12, 5, 14, 7});
18272     }
18273     return DAG.getBitcast(VT, Ex);
18274   };
18275
18276   // Optimize shl/srl/sra with constant shift amount.
18277   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18278     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18279       uint64_t ShiftAmt = ShiftConst->getZExtValue();
18280
18281       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18282         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18283
18284       // i64 SRA needs to be performed as partial shifts.
18285       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18286           Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18287         return ArithmeticShiftRight64(ShiftAmt);
18288
18289       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18290         unsigned NumElts = VT.getVectorNumElements();
18291         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18292
18293         // Simple i8 add case
18294         if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18295           return DAG.getNode(ISD::ADD, dl, VT, R, R);
18296
18297         // ashr(R, 7)  === cmp_slt(R, 0)
18298         if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18299           SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18300           return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18301         }
18302
18303         // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18304         if (VT == MVT::v16i8 && Subtarget->hasXOP())
18305           return SDValue();
18306
18307         if (Op.getOpcode() == ISD::SHL) {
18308           // Make a large shift.
18309           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18310                                                    R, ShiftAmt, DAG);
18311           SHL = DAG.getBitcast(VT, SHL);
18312           // Zero out the rightmost bits.
18313           SmallVector<SDValue, 32> V(
18314               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18315           return DAG.getNode(ISD::AND, dl, VT, SHL,
18316                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18317         }
18318         if (Op.getOpcode() == ISD::SRL) {
18319           // Make a large shift.
18320           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18321                                                    R, ShiftAmt, DAG);
18322           SRL = DAG.getBitcast(VT, SRL);
18323           // Zero out the leftmost bits.
18324           SmallVector<SDValue, 32> V(
18325               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18326           return DAG.getNode(ISD::AND, dl, VT, SRL,
18327                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18328         }
18329         if (Op.getOpcode() == ISD::SRA) {
18330           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18331           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18332           SmallVector<SDValue, 32> V(NumElts,
18333                                      DAG.getConstant(128 >> ShiftAmt, dl,
18334                                                      MVT::i8));
18335           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18336           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18337           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18338           return Res;
18339         }
18340         llvm_unreachable("Unknown shift opcode.");
18341       }
18342     }
18343   }
18344
18345   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18346   if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18347       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18348
18349     // Peek through any splat that was introduced for i64 shift vectorization.
18350     int SplatIndex = -1;
18351     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18352       if (SVN->isSplat()) {
18353         SplatIndex = SVN->getSplatIndex();
18354         Amt = Amt.getOperand(0);
18355         assert(SplatIndex < (int)VT.getVectorNumElements() &&
18356                "Splat shuffle referencing second operand");
18357       }
18358
18359     if (Amt.getOpcode() != ISD::BITCAST ||
18360         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18361       return SDValue();
18362
18363     Amt = Amt.getOperand(0);
18364     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18365                      VT.getVectorNumElements();
18366     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18367     uint64_t ShiftAmt = 0;
18368     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18369     for (unsigned i = 0; i != Ratio; ++i) {
18370       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18371       if (!C)
18372         return SDValue();
18373       // 6 == Log2(64)
18374       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18375     }
18376
18377     // Check remaining shift amounts (if not a splat).
18378     if (SplatIndex < 0) {
18379       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18380         uint64_t ShAmt = 0;
18381         for (unsigned j = 0; j != Ratio; ++j) {
18382           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18383           if (!C)
18384             return SDValue();
18385           // 6 == Log2(64)
18386           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18387         }
18388         if (ShAmt != ShiftAmt)
18389           return SDValue();
18390       }
18391     }
18392
18393     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18394       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18395
18396     if (Op.getOpcode() == ISD::SRA)
18397       return ArithmeticShiftRight64(ShiftAmt);
18398   }
18399
18400   return SDValue();
18401 }
18402
18403 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18404                                         const X86Subtarget* Subtarget) {
18405   MVT VT = Op.getSimpleValueType();
18406   SDLoc dl(Op);
18407   SDValue R = Op.getOperand(0);
18408   SDValue Amt = Op.getOperand(1);
18409
18410   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18411     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18412
18413   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18414     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18415
18416   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18417     SDValue BaseShAmt;
18418     MVT EltVT = VT.getVectorElementType();
18419
18420     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18421       // Check if this build_vector node is doing a splat.
18422       // If so, then set BaseShAmt equal to the splat value.
18423       BaseShAmt = BV->getSplatValue();
18424       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18425         BaseShAmt = SDValue();
18426     } else {
18427       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18428         Amt = Amt.getOperand(0);
18429
18430       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18431       if (SVN && SVN->isSplat()) {
18432         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18433         SDValue InVec = Amt.getOperand(0);
18434         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18435           assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18436                  "Unexpected shuffle index found!");
18437           BaseShAmt = InVec.getOperand(SplatIdx);
18438         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18439            if (ConstantSDNode *C =
18440                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18441              if (C->getZExtValue() == SplatIdx)
18442                BaseShAmt = InVec.getOperand(1);
18443            }
18444         }
18445
18446         if (!BaseShAmt)
18447           // Avoid introducing an extract element from a shuffle.
18448           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18449                                   DAG.getIntPtrConstant(SplatIdx, dl));
18450       }
18451     }
18452
18453     if (BaseShAmt.getNode()) {
18454       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18455       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18456         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18457       else if (EltVT.bitsLT(MVT::i32))
18458         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18459
18460       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18461     }
18462   }
18463
18464   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18465   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
18466       Amt.getOpcode() == ISD::BITCAST &&
18467       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18468     Amt = Amt.getOperand(0);
18469     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18470                      VT.getVectorNumElements();
18471     std::vector<SDValue> Vals(Ratio);
18472     for (unsigned i = 0; i != Ratio; ++i)
18473       Vals[i] = Amt.getOperand(i);
18474     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18475       for (unsigned j = 0; j != Ratio; ++j)
18476         if (Vals[j] != Amt.getOperand(i + j))
18477           return SDValue();
18478     }
18479
18480     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18481       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18482   }
18483   return SDValue();
18484 }
18485
18486 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18487                           SelectionDAG &DAG) {
18488   MVT VT = Op.getSimpleValueType();
18489   SDLoc dl(Op);
18490   SDValue R = Op.getOperand(0);
18491   SDValue Amt = Op.getOperand(1);
18492
18493   assert(VT.isVector() && "Custom lowering only for vector shifts!");
18494   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18495
18496   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18497     return V;
18498
18499   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18500     return V;
18501
18502   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18503     return Op;
18504
18505   // XOP has 128-bit variable logical/arithmetic shifts.
18506   // +ve/-ve Amt = shift left/right.
18507   if (Subtarget->hasXOP() &&
18508       (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18509        VT == MVT::v8i16 || VT == MVT::v16i8)) {
18510     if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18511       SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18512       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18513     }
18514     if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18515       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18516     if (Op.getOpcode() == ISD::SRA)
18517       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18518   }
18519
18520   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18521   // shifts per-lane and then shuffle the partial results back together.
18522   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18523     // Splat the shift amounts so the scalar shifts above will catch it.
18524     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18525     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18526     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18527     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18528     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18529   }
18530
18531   // i64 vector arithmetic shift can be emulated with the transform:
18532   // M = lshr(SIGN_BIT, Amt)
18533   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18534   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18535       Op.getOpcode() == ISD::SRA) {
18536     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18537     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18538     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18539     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18540     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18541     return R;
18542   }
18543
18544   // If possible, lower this packed shift into a vector multiply instead of
18545   // expanding it into a sequence of scalar shifts.
18546   // Do this only if the vector shift count is a constant build_vector.
18547   if (Op.getOpcode() == ISD::SHL &&
18548       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18549        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18550       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18551     SmallVector<SDValue, 8> Elts;
18552     MVT SVT = VT.getVectorElementType();
18553     unsigned SVTBits = SVT.getSizeInBits();
18554     APInt One(SVTBits, 1);
18555     unsigned NumElems = VT.getVectorNumElements();
18556
18557     for (unsigned i=0; i !=NumElems; ++i) {
18558       SDValue Op = Amt->getOperand(i);
18559       if (Op->getOpcode() == ISD::UNDEF) {
18560         Elts.push_back(Op);
18561         continue;
18562       }
18563
18564       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18565       APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18566       uint64_t ShAmt = C.getZExtValue();
18567       if (ShAmt >= SVTBits) {
18568         Elts.push_back(DAG.getUNDEF(SVT));
18569         continue;
18570       }
18571       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18572     }
18573     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18574     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18575   }
18576
18577   // Lower SHL with variable shift amount.
18578   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18579     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18580
18581     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18582                      DAG.getConstant(0x3f800000U, dl, VT));
18583     Op = DAG.getBitcast(MVT::v4f32, Op);
18584     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18585     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18586   }
18587
18588   // If possible, lower this shift as a sequence of two shifts by
18589   // constant plus a MOVSS/MOVSD instead of scalarizing it.
18590   // Example:
18591   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18592   //
18593   // Could be rewritten as:
18594   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18595   //
18596   // The advantage is that the two shifts from the example would be
18597   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18598   // the vector shift into four scalar shifts plus four pairs of vector
18599   // insert/extract.
18600   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18601       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18602     unsigned TargetOpcode = X86ISD::MOVSS;
18603     bool CanBeSimplified;
18604     // The splat value for the first packed shift (the 'X' from the example).
18605     SDValue Amt1 = Amt->getOperand(0);
18606     // The splat value for the second packed shift (the 'Y' from the example).
18607     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18608                                         Amt->getOperand(2);
18609
18610     // See if it is possible to replace this node with a sequence of
18611     // two shifts followed by a MOVSS/MOVSD
18612     if (VT == MVT::v4i32) {
18613       // Check if it is legal to use a MOVSS.
18614       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18615                         Amt2 == Amt->getOperand(3);
18616       if (!CanBeSimplified) {
18617         // Otherwise, check if we can still simplify this node using a MOVSD.
18618         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18619                           Amt->getOperand(2) == Amt->getOperand(3);
18620         TargetOpcode = X86ISD::MOVSD;
18621         Amt2 = Amt->getOperand(2);
18622       }
18623     } else {
18624       // Do similar checks for the case where the machine value type
18625       // is MVT::v8i16.
18626       CanBeSimplified = Amt1 == Amt->getOperand(1);
18627       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18628         CanBeSimplified = Amt2 == Amt->getOperand(i);
18629
18630       if (!CanBeSimplified) {
18631         TargetOpcode = X86ISD::MOVSD;
18632         CanBeSimplified = true;
18633         Amt2 = Amt->getOperand(4);
18634         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18635           CanBeSimplified = Amt1 == Amt->getOperand(i);
18636         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18637           CanBeSimplified = Amt2 == Amt->getOperand(j);
18638       }
18639     }
18640
18641     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18642         isa<ConstantSDNode>(Amt2)) {
18643       // Replace this node with two shifts followed by a MOVSS/MOVSD.
18644       MVT CastVT = MVT::v4i32;
18645       SDValue Splat1 =
18646         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18647       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18648       SDValue Splat2 =
18649         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18650       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18651       if (TargetOpcode == X86ISD::MOVSD)
18652         CastVT = MVT::v2i64;
18653       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18654       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18655       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18656                                             BitCast1, DAG);
18657       return DAG.getBitcast(VT, Result);
18658     }
18659   }
18660
18661   // v4i32 Non Uniform Shifts.
18662   // If the shift amount is constant we can shift each lane using the SSE2
18663   // immediate shifts, else we need to zero-extend each lane to the lower i64
18664   // and shift using the SSE2 variable shifts.
18665   // The separate results can then be blended together.
18666   if (VT == MVT::v4i32) {
18667     unsigned Opc = Op.getOpcode();
18668     SDValue Amt0, Amt1, Amt2, Amt3;
18669     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18670       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18671       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18672       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18673       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18674     } else {
18675       // ISD::SHL is handled above but we include it here for completeness.
18676       switch (Opc) {
18677       default:
18678         llvm_unreachable("Unknown target vector shift node");
18679       case ISD::SHL:
18680         Opc = X86ISD::VSHL;
18681         break;
18682       case ISD::SRL:
18683         Opc = X86ISD::VSRL;
18684         break;
18685       case ISD::SRA:
18686         Opc = X86ISD::VSRA;
18687         break;
18688       }
18689       // The SSE2 shifts use the lower i64 as the same shift amount for
18690       // all lanes and the upper i64 is ignored. These shuffle masks
18691       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18692       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18693       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18694       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18695       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18696       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18697     }
18698
18699     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18700     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18701     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18702     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18703     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18704     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18705     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18706   }
18707
18708   if (VT == MVT::v16i8 ||
18709       (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18710     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18711     unsigned ShiftOpcode = Op->getOpcode();
18712
18713     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18714       // On SSE41 targets we make use of the fact that VSELECT lowers
18715       // to PBLENDVB which selects bytes based just on the sign bit.
18716       if (Subtarget->hasSSE41()) {
18717         V0 = DAG.getBitcast(VT, V0);
18718         V1 = DAG.getBitcast(VT, V1);
18719         Sel = DAG.getBitcast(VT, Sel);
18720         return DAG.getBitcast(SelVT,
18721                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18722       }
18723       // On pre-SSE41 targets we test for the sign bit by comparing to
18724       // zero - a negative value will set all bits of the lanes to true
18725       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18726       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18727       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18728       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18729     };
18730
18731     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18732     // We can safely do this using i16 shifts as we're only interested in
18733     // the 3 lower bits of each byte.
18734     Amt = DAG.getBitcast(ExtVT, Amt);
18735     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18736     Amt = DAG.getBitcast(VT, Amt);
18737
18738     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18739       // r = VSELECT(r, shift(r, 4), a);
18740       SDValue M =
18741           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18742       R = SignBitSelect(VT, Amt, M, R);
18743
18744       // a += a
18745       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18746
18747       // r = VSELECT(r, shift(r, 2), a);
18748       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18749       R = SignBitSelect(VT, Amt, M, R);
18750
18751       // a += a
18752       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18753
18754       // return VSELECT(r, shift(r, 1), a);
18755       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18756       R = SignBitSelect(VT, Amt, M, R);
18757       return R;
18758     }
18759
18760     if (Op->getOpcode() == ISD::SRA) {
18761       // For SRA we need to unpack each byte to the higher byte of a i16 vector
18762       // so we can correctly sign extend. We don't care what happens to the
18763       // lower byte.
18764       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18765       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18766       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18767       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18768       ALo = DAG.getBitcast(ExtVT, ALo);
18769       AHi = DAG.getBitcast(ExtVT, AHi);
18770       RLo = DAG.getBitcast(ExtVT, RLo);
18771       RHi = DAG.getBitcast(ExtVT, RHi);
18772
18773       // r = VSELECT(r, shift(r, 4), a);
18774       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18775                                 DAG.getConstant(4, dl, ExtVT));
18776       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18777                                 DAG.getConstant(4, dl, ExtVT));
18778       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18779       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18780
18781       // a += a
18782       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18783       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18784
18785       // r = VSELECT(r, shift(r, 2), a);
18786       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18787                         DAG.getConstant(2, dl, ExtVT));
18788       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18789                         DAG.getConstant(2, dl, ExtVT));
18790       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18791       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18792
18793       // a += a
18794       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18795       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18796
18797       // r = VSELECT(r, shift(r, 1), a);
18798       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18799                         DAG.getConstant(1, dl, ExtVT));
18800       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18801                         DAG.getConstant(1, dl, ExtVT));
18802       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18803       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18804
18805       // Logical shift the result back to the lower byte, leaving a zero upper
18806       // byte
18807       // meaning that we can safely pack with PACKUSWB.
18808       RLo =
18809           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18810       RHi =
18811           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18812       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18813     }
18814   }
18815
18816   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18817   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18818   // solution better.
18819   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18820     MVT ExtVT = MVT::v8i32;
18821     unsigned ExtOpc =
18822         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18823     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18824     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18825     return DAG.getNode(ISD::TRUNCATE, dl, VT,
18826                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18827   }
18828
18829   if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18830     MVT ExtVT = MVT::v8i32;
18831     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18832     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18833     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18834     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18835     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18836     ALo = DAG.getBitcast(ExtVT, ALo);
18837     AHi = DAG.getBitcast(ExtVT, AHi);
18838     RLo = DAG.getBitcast(ExtVT, RLo);
18839     RHi = DAG.getBitcast(ExtVT, RHi);
18840     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18841     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18842     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18843     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18844     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18845   }
18846
18847   if (VT == MVT::v8i16) {
18848     unsigned ShiftOpcode = Op->getOpcode();
18849
18850     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18851       // On SSE41 targets we make use of the fact that VSELECT lowers
18852       // to PBLENDVB which selects bytes based just on the sign bit.
18853       if (Subtarget->hasSSE41()) {
18854         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18855         V0 = DAG.getBitcast(ExtVT, V0);
18856         V1 = DAG.getBitcast(ExtVT, V1);
18857         Sel = DAG.getBitcast(ExtVT, Sel);
18858         return DAG.getBitcast(
18859             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18860       }
18861       // On pre-SSE41 targets we splat the sign bit - a negative value will
18862       // set all bits of the lanes to true and VSELECT uses that in
18863       // its OR(AND(V0,C),AND(V1,~C)) lowering.
18864       SDValue C =
18865           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18866       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18867     };
18868
18869     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18870     if (Subtarget->hasSSE41()) {
18871       // On SSE41 targets we need to replicate the shift mask in both
18872       // bytes for PBLENDVB.
18873       Amt = DAG.getNode(
18874           ISD::OR, dl, VT,
18875           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18876           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18877     } else {
18878       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18879     }
18880
18881     // r = VSELECT(r, shift(r, 8), a);
18882     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18883     R = SignBitSelect(Amt, M, R);
18884
18885     // a += a
18886     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18887
18888     // r = VSELECT(r, shift(r, 4), a);
18889     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18890     R = SignBitSelect(Amt, M, R);
18891
18892     // a += a
18893     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18894
18895     // r = VSELECT(r, shift(r, 2), a);
18896     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18897     R = SignBitSelect(Amt, M, R);
18898
18899     // a += a
18900     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18901
18902     // return VSELECT(r, shift(r, 1), a);
18903     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18904     R = SignBitSelect(Amt, M, R);
18905     return R;
18906   }
18907
18908   // Decompose 256-bit shifts into smaller 128-bit shifts.
18909   if (VT.is256BitVector()) {
18910     unsigned NumElems = VT.getVectorNumElements();
18911     MVT EltVT = VT.getVectorElementType();
18912     MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18913
18914     // Extract the two vectors
18915     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18916     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18917
18918     // Recreate the shift amount vectors
18919     SDValue Amt1, Amt2;
18920     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18921       // Constant shift amount
18922       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18923       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18924       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18925
18926       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18927       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18928     } else {
18929       // Variable shift amount
18930       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18931       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18932     }
18933
18934     // Issue new vector shifts for the smaller types
18935     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18936     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18937
18938     // Concatenate the result back
18939     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18940   }
18941
18942   return SDValue();
18943 }
18944
18945 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
18946                            SelectionDAG &DAG) {
18947   MVT VT = Op.getSimpleValueType();
18948   SDLoc DL(Op);
18949   SDValue R = Op.getOperand(0);
18950   SDValue Amt = Op.getOperand(1);
18951
18952   assert(VT.isVector() && "Custom lowering only for vector rotates!");
18953   assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
18954   assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
18955
18956   // XOP has 128-bit vector variable + immediate rotates.
18957   // +ve/-ve Amt = rotate left/right.
18958
18959   // Split 256-bit integers.
18960   if (VT.is256BitVector())
18961     return Lower256IntArith(Op, DAG);
18962
18963   assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
18964
18965   // Attempt to rotate by immediate.
18966   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18967     if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
18968       uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
18969       assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
18970       return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
18971                          DAG.getConstant(RotateAmt, DL, MVT::i8));
18972     }
18973   }
18974
18975   // Use general rotate by variable (per-element).
18976   return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
18977 }
18978
18979 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18980   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18981   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18982   // looks for this combo and may remove the "setcc" instruction if the "setcc"
18983   // has only one use.
18984   SDNode *N = Op.getNode();
18985   SDValue LHS = N->getOperand(0);
18986   SDValue RHS = N->getOperand(1);
18987   unsigned BaseOp = 0;
18988   unsigned Cond = 0;
18989   SDLoc DL(Op);
18990   switch (Op.getOpcode()) {
18991   default: llvm_unreachable("Unknown ovf instruction!");
18992   case ISD::SADDO:
18993     // A subtract of one will be selected as a INC. Note that INC doesn't
18994     // set CF, so we can't do this for UADDO.
18995     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18996       if (C->isOne()) {
18997         BaseOp = X86ISD::INC;
18998         Cond = X86::COND_O;
18999         break;
19000       }
19001     BaseOp = X86ISD::ADD;
19002     Cond = X86::COND_O;
19003     break;
19004   case ISD::UADDO:
19005     BaseOp = X86ISD::ADD;
19006     Cond = X86::COND_B;
19007     break;
19008   case ISD::SSUBO:
19009     // A subtract of one will be selected as a DEC. Note that DEC doesn't
19010     // set CF, so we can't do this for USUBO.
19011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
19012       if (C->isOne()) {
19013         BaseOp = X86ISD::DEC;
19014         Cond = X86::COND_O;
19015         break;
19016       }
19017     BaseOp = X86ISD::SUB;
19018     Cond = X86::COND_O;
19019     break;
19020   case ISD::USUBO:
19021     BaseOp = X86ISD::SUB;
19022     Cond = X86::COND_B;
19023     break;
19024   case ISD::SMULO:
19025     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19026     Cond = X86::COND_O;
19027     break;
19028   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19029     if (N->getValueType(0) == MVT::i8) {
19030       BaseOp = X86ISD::UMUL8;
19031       Cond = X86::COND_O;
19032       break;
19033     }
19034     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19035                                  MVT::i32);
19036     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19037
19038     SDValue SetCC =
19039       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19040                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
19041                   SDValue(Sum.getNode(), 2));
19042
19043     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19044   }
19045   }
19046
19047   // Also sets EFLAGS.
19048   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19049   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19050
19051   SDValue SetCC =
19052     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19053                 DAG.getConstant(Cond, DL, MVT::i32),
19054                 SDValue(Sum.getNode(), 1));
19055
19056   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19057 }
19058
19059 /// Returns true if the operand type is exactly twice the native width, and
19060 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19061 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19062 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19063 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19064   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19065
19066   if (OpWidth == 64)
19067     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19068   else if (OpWidth == 128)
19069     return Subtarget->hasCmpxchg16b();
19070   else
19071     return false;
19072 }
19073
19074 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19075   return needsCmpXchgNb(SI->getValueOperand()->getType());
19076 }
19077
19078 // Note: this turns large loads into lock cmpxchg8b/16b.
19079 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19080 TargetLowering::AtomicExpansionKind
19081 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19082   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19083   return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19084                                                : AtomicExpansionKind::None;
19085 }
19086
19087 TargetLowering::AtomicExpansionKind
19088 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19089   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19090   Type *MemType = AI->getType();
19091
19092   // If the operand is too big, we must see if cmpxchg8/16b is available
19093   // and default to library calls otherwise.
19094   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19095     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19096                                    : AtomicExpansionKind::None;
19097   }
19098
19099   AtomicRMWInst::BinOp Op = AI->getOperation();
19100   switch (Op) {
19101   default:
19102     llvm_unreachable("Unknown atomic operation");
19103   case AtomicRMWInst::Xchg:
19104   case AtomicRMWInst::Add:
19105   case AtomicRMWInst::Sub:
19106     // It's better to use xadd, xsub or xchg for these in all cases.
19107     return AtomicExpansionKind::None;
19108   case AtomicRMWInst::Or:
19109   case AtomicRMWInst::And:
19110   case AtomicRMWInst::Xor:
19111     // If the atomicrmw's result isn't actually used, we can just add a "lock"
19112     // prefix to a normal instruction for these operations.
19113     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19114                             : AtomicExpansionKind::None;
19115   case AtomicRMWInst::Nand:
19116   case AtomicRMWInst::Max:
19117   case AtomicRMWInst::Min:
19118   case AtomicRMWInst::UMax:
19119   case AtomicRMWInst::UMin:
19120     // These always require a non-trivial set of data operations on x86. We must
19121     // use a cmpxchg loop.
19122     return AtomicExpansionKind::CmpXChg;
19123   }
19124 }
19125
19126 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19127   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19128   // no-sse2). There isn't any reason to disable it if the target processor
19129   // supports it.
19130   return Subtarget.hasSSE2() || Subtarget.is64Bit();
19131 }
19132
19133 LoadInst *
19134 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19135   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19136   Type *MemType = AI->getType();
19137   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19138   // there is no benefit in turning such RMWs into loads, and it is actually
19139   // harmful as it introduces a mfence.
19140   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19141     return nullptr;
19142
19143   auto Builder = IRBuilder<>(AI);
19144   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19145   auto SynchScope = AI->getSynchScope();
19146   // We must restrict the ordering to avoid generating loads with Release or
19147   // ReleaseAcquire orderings.
19148   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19149   auto Ptr = AI->getPointerOperand();
19150
19151   // Before the load we need a fence. Here is an example lifted from
19152   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19153   // is required:
19154   // Thread 0:
19155   //   x.store(1, relaxed);
19156   //   r1 = y.fetch_add(0, release);
19157   // Thread 1:
19158   //   y.fetch_add(42, acquire);
19159   //   r2 = x.load(relaxed);
19160   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19161   // lowered to just a load without a fence. A mfence flushes the store buffer,
19162   // making the optimization clearly correct.
19163   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19164   // otherwise, we might be able to be more aggressive on relaxed idempotent
19165   // rmw. In practice, they do not look useful, so we don't try to be
19166   // especially clever.
19167   if (SynchScope == SingleThread)
19168     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19169     // the IR level, so we must wrap it in an intrinsic.
19170     return nullptr;
19171
19172   if (!hasMFENCE(*Subtarget))
19173     // FIXME: it might make sense to use a locked operation here but on a
19174     // different cache-line to prevent cache-line bouncing. In practice it
19175     // is probably a small win, and x86 processors without mfence are rare
19176     // enough that we do not bother.
19177     return nullptr;
19178
19179   Function *MFence =
19180       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19181   Builder.CreateCall(MFence, {});
19182
19183   // Finally we can emit the atomic load.
19184   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19185           AI->getType()->getPrimitiveSizeInBits());
19186   Loaded->setAtomic(Order, SynchScope);
19187   AI->replaceAllUsesWith(Loaded);
19188   AI->eraseFromParent();
19189   return Loaded;
19190 }
19191
19192 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19193                                  SelectionDAG &DAG) {
19194   SDLoc dl(Op);
19195   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19196     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19197   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19198     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19199
19200   // The only fence that needs an instruction is a sequentially-consistent
19201   // cross-thread fence.
19202   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19203     if (hasMFENCE(*Subtarget))
19204       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19205
19206     SDValue Chain = Op.getOperand(0);
19207     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19208     SDValue Ops[] = {
19209       DAG.getRegister(X86::ESP, MVT::i32),     // Base
19210       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
19211       DAG.getRegister(0, MVT::i32),            // Index
19212       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
19213       DAG.getRegister(0, MVT::i32),            // Segment.
19214       Zero,
19215       Chain
19216     };
19217     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19218     return SDValue(Res, 0);
19219   }
19220
19221   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19222   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19223 }
19224
19225 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19226                              SelectionDAG &DAG) {
19227   MVT T = Op.getSimpleValueType();
19228   SDLoc DL(Op);
19229   unsigned Reg = 0;
19230   unsigned size = 0;
19231   switch(T.SimpleTy) {
19232   default: llvm_unreachable("Invalid value type!");
19233   case MVT::i8:  Reg = X86::AL;  size = 1; break;
19234   case MVT::i16: Reg = X86::AX;  size = 2; break;
19235   case MVT::i32: Reg = X86::EAX; size = 4; break;
19236   case MVT::i64:
19237     assert(Subtarget->is64Bit() && "Node not type legal!");
19238     Reg = X86::RAX; size = 8;
19239     break;
19240   }
19241   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19242                                   Op.getOperand(2), SDValue());
19243   SDValue Ops[] = { cpIn.getValue(0),
19244                     Op.getOperand(1),
19245                     Op.getOperand(3),
19246                     DAG.getTargetConstant(size, DL, MVT::i8),
19247                     cpIn.getValue(1) };
19248   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19249   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19250   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19251                                            Ops, T, MMO);
19252
19253   SDValue cpOut =
19254     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19255   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19256                                       MVT::i32, cpOut.getValue(2));
19257   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19258                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19259                                 EFLAGS);
19260
19261   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19262   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19263   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19264   return SDValue();
19265 }
19266
19267 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19268                             SelectionDAG &DAG) {
19269   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19270   MVT DstVT = Op.getSimpleValueType();
19271
19272   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19273     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19274     if (DstVT != MVT::f64)
19275       // This conversion needs to be expanded.
19276       return SDValue();
19277
19278     SDValue InVec = Op->getOperand(0);
19279     SDLoc dl(Op);
19280     unsigned NumElts = SrcVT.getVectorNumElements();
19281     MVT SVT = SrcVT.getVectorElementType();
19282
19283     // Widen the vector in input in the case of MVT::v2i32.
19284     // Example: from MVT::v2i32 to MVT::v4i32.
19285     SmallVector<SDValue, 16> Elts;
19286     for (unsigned i = 0, e = NumElts; i != e; ++i)
19287       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19288                                  DAG.getIntPtrConstant(i, dl)));
19289
19290     // Explicitly mark the extra elements as Undef.
19291     Elts.append(NumElts, DAG.getUNDEF(SVT));
19292
19293     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19294     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19295     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19296     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19297                        DAG.getIntPtrConstant(0, dl));
19298   }
19299
19300   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19301          Subtarget->hasMMX() && "Unexpected custom BITCAST");
19302   assert((DstVT == MVT::i64 ||
19303           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19304          "Unexpected custom BITCAST");
19305   // i64 <=> MMX conversions are Legal.
19306   if (SrcVT==MVT::i64 && DstVT.isVector())
19307     return Op;
19308   if (DstVT==MVT::i64 && SrcVT.isVector())
19309     return Op;
19310   // MMX <=> MMX conversions are Legal.
19311   if (SrcVT.isVector() && DstVT.isVector())
19312     return Op;
19313   // All other conversions need to be expanded.
19314   return SDValue();
19315 }
19316
19317 /// Compute the horizontal sum of bytes in V for the elements of VT.
19318 ///
19319 /// Requires V to be a byte vector and VT to be an integer vector type with
19320 /// wider elements than V's type. The width of the elements of VT determines
19321 /// how many bytes of V are summed horizontally to produce each element of the
19322 /// result.
19323 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19324                                       const X86Subtarget *Subtarget,
19325                                       SelectionDAG &DAG) {
19326   SDLoc DL(V);
19327   MVT ByteVecVT = V.getSimpleValueType();
19328   MVT EltVT = VT.getVectorElementType();
19329   int NumElts = VT.getVectorNumElements();
19330   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19331          "Expected value to have byte element type.");
19332   assert(EltVT != MVT::i8 &&
19333          "Horizontal byte sum only makes sense for wider elements!");
19334   unsigned VecSize = VT.getSizeInBits();
19335   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19336
19337   // PSADBW instruction horizontally add all bytes and leave the result in i64
19338   // chunks, thus directly computes the pop count for v2i64 and v4i64.
19339   if (EltVT == MVT::i64) {
19340     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19341     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19342     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19343     return DAG.getBitcast(VT, V);
19344   }
19345
19346   if (EltVT == MVT::i32) {
19347     // We unpack the low half and high half into i32s interleaved with zeros so
19348     // that we can use PSADBW to horizontally sum them. The most useful part of
19349     // this is that it lines up the results of two PSADBW instructions to be
19350     // two v2i64 vectors which concatenated are the 4 population counts. We can
19351     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19352     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19353     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19354     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19355
19356     // Do the horizontal sums into two v2i64s.
19357     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19358     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19359     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19360                       DAG.getBitcast(ByteVecVT, Low), Zeros);
19361     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19362                        DAG.getBitcast(ByteVecVT, High), Zeros);
19363
19364     // Merge them together.
19365     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19366     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19367                     DAG.getBitcast(ShortVecVT, Low),
19368                     DAG.getBitcast(ShortVecVT, High));
19369
19370     return DAG.getBitcast(VT, V);
19371   }
19372
19373   // The only element type left is i16.
19374   assert(EltVT == MVT::i16 && "Unknown how to handle type");
19375
19376   // To obtain pop count for each i16 element starting from the pop count for
19377   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19378   // right by 8. It is important to shift as i16s as i8 vector shift isn't
19379   // directly supported.
19380   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19381   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19382   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19383   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19384                   DAG.getBitcast(ByteVecVT, V));
19385   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19386 }
19387
19388 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19389                                         const X86Subtarget *Subtarget,
19390                                         SelectionDAG &DAG) {
19391   MVT VT = Op.getSimpleValueType();
19392   MVT EltVT = VT.getVectorElementType();
19393   unsigned VecSize = VT.getSizeInBits();
19394
19395   // Implement a lookup table in register by using an algorithm based on:
19396   // http://wm.ite.pl/articles/sse-popcount.html
19397   //
19398   // The general idea is that every lower byte nibble in the input vector is an
19399   // index into a in-register pre-computed pop count table. We then split up the
19400   // input vector in two new ones: (1) a vector with only the shifted-right
19401   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19402   // masked out higher ones) for each byte. PSHUB is used separately with both
19403   // to index the in-register table. Next, both are added and the result is a
19404   // i8 vector where each element contains the pop count for input byte.
19405   //
19406   // To obtain the pop count for elements != i8, we follow up with the same
19407   // approach and use additional tricks as described below.
19408   //
19409   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19410                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19411                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19412                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19413
19414   int NumByteElts = VecSize / 8;
19415   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19416   SDValue In = DAG.getBitcast(ByteVecVT, Op);
19417   SmallVector<SDValue, 16> LUTVec;
19418   for (int i = 0; i < NumByteElts; ++i)
19419     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19420   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19421   SmallVector<SDValue, 16> Mask0F(NumByteElts,
19422                                   DAG.getConstant(0x0F, DL, MVT::i8));
19423   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19424
19425   // High nibbles
19426   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19427   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19428   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19429
19430   // Low nibbles
19431   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19432
19433   // The input vector is used as the shuffle mask that index elements into the
19434   // LUT. After counting low and high nibbles, add the vector to obtain the
19435   // final pop count per i8 element.
19436   SDValue HighPopCnt =
19437       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19438   SDValue LowPopCnt =
19439       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19440   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19441
19442   if (EltVT == MVT::i8)
19443     return PopCnt;
19444
19445   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19446 }
19447
19448 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19449                                        const X86Subtarget *Subtarget,
19450                                        SelectionDAG &DAG) {
19451   MVT VT = Op.getSimpleValueType();
19452   assert(VT.is128BitVector() &&
19453          "Only 128-bit vector bitmath lowering supported.");
19454
19455   int VecSize = VT.getSizeInBits();
19456   MVT EltVT = VT.getVectorElementType();
19457   int Len = EltVT.getSizeInBits();
19458
19459   // This is the vectorized version of the "best" algorithm from
19460   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19461   // with a minor tweak to use a series of adds + shifts instead of vector
19462   // multiplications. Implemented for all integer vector types. We only use
19463   // this when we don't have SSSE3 which allows a LUT-based lowering that is
19464   // much faster, even faster than using native popcnt instructions.
19465
19466   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19467     MVT VT = V.getSimpleValueType();
19468     SmallVector<SDValue, 32> Shifters(
19469         VT.getVectorNumElements(),
19470         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19471     return DAG.getNode(OpCode, DL, VT, V,
19472                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19473   };
19474   auto GetMask = [&](SDValue V, APInt Mask) {
19475     MVT VT = V.getSimpleValueType();
19476     SmallVector<SDValue, 32> Masks(
19477         VT.getVectorNumElements(),
19478         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19479     return DAG.getNode(ISD::AND, DL, VT, V,
19480                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19481   };
19482
19483   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19484   // x86, so set the SRL type to have elements at least i16 wide. This is
19485   // correct because all of our SRLs are followed immediately by a mask anyways
19486   // that handles any bits that sneak into the high bits of the byte elements.
19487   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19488
19489   SDValue V = Op;
19490
19491   // v = v - ((v >> 1) & 0x55555555...)
19492   SDValue Srl =
19493       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19494   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19495   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19496
19497   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19498   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19499   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19500   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19501   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19502
19503   // v = (v + (v >> 4)) & 0x0F0F0F0F...
19504   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19505   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19506   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19507
19508   // At this point, V contains the byte-wise population count, and we are
19509   // merely doing a horizontal sum if necessary to get the wider element
19510   // counts.
19511   if (EltVT == MVT::i8)
19512     return V;
19513
19514   return LowerHorizontalByteSum(
19515       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19516       DAG);
19517 }
19518
19519 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19520                                 SelectionDAG &DAG) {
19521   MVT VT = Op.getSimpleValueType();
19522   // FIXME: Need to add AVX-512 support here!
19523   assert((VT.is256BitVector() || VT.is128BitVector()) &&
19524          "Unknown CTPOP type to handle");
19525   SDLoc DL(Op.getNode());
19526   SDValue Op0 = Op.getOperand(0);
19527
19528   if (!Subtarget->hasSSSE3()) {
19529     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19530     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19531     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19532   }
19533
19534   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19535     unsigned NumElems = VT.getVectorNumElements();
19536
19537     // Extract each 128-bit vector, compute pop count and concat the result.
19538     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19539     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19540
19541     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19542                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19543                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19544   }
19545
19546   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19547 }
19548
19549 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19550                           SelectionDAG &DAG) {
19551   assert(Op.getSimpleValueType().isVector() &&
19552          "We only do custom lowering for vector population count.");
19553   return LowerVectorCTPOP(Op, Subtarget, DAG);
19554 }
19555
19556 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19557   SDNode *Node = Op.getNode();
19558   SDLoc dl(Node);
19559   EVT T = Node->getValueType(0);
19560   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19561                               DAG.getConstant(0, dl, T), Node->getOperand(2));
19562   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19563                        cast<AtomicSDNode>(Node)->getMemoryVT(),
19564                        Node->getOperand(0),
19565                        Node->getOperand(1), negOp,
19566                        cast<AtomicSDNode>(Node)->getMemOperand(),
19567                        cast<AtomicSDNode>(Node)->getOrdering(),
19568                        cast<AtomicSDNode>(Node)->getSynchScope());
19569 }
19570
19571 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19572   SDNode *Node = Op.getNode();
19573   SDLoc dl(Node);
19574   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19575
19576   // Convert seq_cst store -> xchg
19577   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19578   // FIXME: On 32-bit, store -> fist or movq would be more efficient
19579   //        (The only way to get a 16-byte store is cmpxchg16b)
19580   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19581   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19582       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19583     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19584                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
19585                                  Node->getOperand(0),
19586                                  Node->getOperand(1), Node->getOperand(2),
19587                                  cast<AtomicSDNode>(Node)->getMemOperand(),
19588                                  cast<AtomicSDNode>(Node)->getOrdering(),
19589                                  cast<AtomicSDNode>(Node)->getSynchScope());
19590     return Swap.getValue(1);
19591   }
19592   // Other atomic stores have a simple pattern.
19593   return Op;
19594 }
19595
19596 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19597   MVT VT = Op.getNode()->getSimpleValueType(0);
19598
19599   // Let legalize expand this if it isn't a legal type yet.
19600   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19601     return SDValue();
19602
19603   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19604
19605   unsigned Opc;
19606   bool ExtraOp = false;
19607   switch (Op.getOpcode()) {
19608   default: llvm_unreachable("Invalid code");
19609   case ISD::ADDC: Opc = X86ISD::ADD; break;
19610   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19611   case ISD::SUBC: Opc = X86ISD::SUB; break;
19612   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19613   }
19614
19615   if (!ExtraOp)
19616     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19617                        Op.getOperand(1));
19618   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19619                      Op.getOperand(1), Op.getOperand(2));
19620 }
19621
19622 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19623                             SelectionDAG &DAG) {
19624   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19625
19626   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19627   // which returns the values as { float, float } (in XMM0) or
19628   // { double, double } (which is returned in XMM0, XMM1).
19629   SDLoc dl(Op);
19630   SDValue Arg = Op.getOperand(0);
19631   EVT ArgVT = Arg.getValueType();
19632   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19633
19634   TargetLowering::ArgListTy Args;
19635   TargetLowering::ArgListEntry Entry;
19636
19637   Entry.Node = Arg;
19638   Entry.Ty = ArgTy;
19639   Entry.isSExt = false;
19640   Entry.isZExt = false;
19641   Args.push_back(Entry);
19642
19643   bool isF64 = ArgVT == MVT::f64;
19644   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19645   // the small struct {f32, f32} is returned in (eax, edx). For f64,
19646   // the results are returned via SRet in memory.
19647   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
19648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19649   SDValue Callee =
19650       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19651
19652   Type *RetTy = isF64
19653     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19654     : (Type*)VectorType::get(ArgTy, 4);
19655
19656   TargetLowering::CallLoweringInfo CLI(DAG);
19657   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19658     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19659
19660   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19661
19662   if (isF64)
19663     // Returned in xmm0 and xmm1.
19664     return CallResult.first;
19665
19666   // Returned in bits 0:31 and 32:64 xmm0.
19667   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19668                                CallResult.first, DAG.getIntPtrConstant(0, dl));
19669   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19670                                CallResult.first, DAG.getIntPtrConstant(1, dl));
19671   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19672   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19673 }
19674
19675 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19676                              SelectionDAG &DAG) {
19677   assert(Subtarget->hasAVX512() &&
19678          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19679
19680   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19681   MVT VT = N->getValue().getSimpleValueType();
19682   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19683   SDLoc dl(Op);
19684
19685   // X86 scatter kills mask register, so its type should be added to
19686   // the list of return values
19687   if (N->getNumValues() == 1) {
19688     SDValue Index = N->getIndex();
19689     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19690         !Index.getSimpleValueType().is512BitVector())
19691       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19692
19693     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19694     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19695                       N->getOperand(3), Index };
19696
19697     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19698     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19699     return SDValue(NewScatter.getNode(), 0);
19700   }
19701   return Op;
19702 }
19703
19704 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19705                             SelectionDAG &DAG) {
19706   assert(Subtarget->hasAVX512() &&
19707          "MGATHER/MSCATTER are supported on AVX-512 arch only");
19708
19709   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19710   MVT VT = Op.getSimpleValueType();
19711   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19712   SDLoc dl(Op);
19713
19714   SDValue Index = N->getIndex();
19715   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19716       !Index.getSimpleValueType().is512BitVector()) {
19717     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19718     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
19719                       N->getOperand(3), Index };
19720     DAG.UpdateNodeOperands(N, Ops);
19721   }
19722   return Op;
19723 }
19724
19725 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19726                                                     SelectionDAG &DAG) const {
19727   // TODO: Eventually, the lowering of these nodes should be informed by or
19728   // deferred to the GC strategy for the function in which they appear. For
19729   // now, however, they must be lowered to something. Since they are logically
19730   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19731   // require special handling for these nodes), lower them as literal NOOPs for
19732   // the time being.
19733   SmallVector<SDValue, 2> Ops;
19734
19735   Ops.push_back(Op.getOperand(0));
19736   if (Op->getGluedNode())
19737     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19738
19739   SDLoc OpDL(Op);
19740   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19741   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19742
19743   return NOOP;
19744 }
19745
19746 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19747                                                   SelectionDAG &DAG) const {
19748   // TODO: Eventually, the lowering of these nodes should be informed by or
19749   // deferred to the GC strategy for the function in which they appear. For
19750   // now, however, they must be lowered to something. Since they are logically
19751   // no-ops in the case of a null GC strategy (or a GC strategy which does not
19752   // require special handling for these nodes), lower them as literal NOOPs for
19753   // the time being.
19754   SmallVector<SDValue, 2> Ops;
19755
19756   Ops.push_back(Op.getOperand(0));
19757   if (Op->getGluedNode())
19758     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19759
19760   SDLoc OpDL(Op);
19761   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19762   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19763
19764   return NOOP;
19765 }
19766
19767 /// LowerOperation - Provide custom lowering hooks for some operations.
19768 ///
19769 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19770   switch (Op.getOpcode()) {
19771   default: llvm_unreachable("Should not custom lower this!");
19772   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19773   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19774     return LowerCMP_SWAP(Op, Subtarget, DAG);
19775   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
19776   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
19777   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
19778   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
19779   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19780   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
19781   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
19782   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19783   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
19784   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19785   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19786   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
19787   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
19788   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
19789   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
19790   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
19791   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
19792   case ISD::SHL_PARTS:
19793   case ISD::SRA_PARTS:
19794   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
19795   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
19796   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
19797   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
19798   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
19799   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19800   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
19801   case ISD::SIGN_EXTEND_VECTOR_INREG:
19802     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19803   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
19804   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
19805   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
19806   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
19807   case ISD::FABS:
19808   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
19809   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
19810   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
19811   case ISD::SETCC:              return LowerSETCC(Op, DAG);
19812   case ISD::SETCCE:             return LowerSETCCE(Op, DAG);
19813   case ISD::SELECT:             return LowerSELECT(Op, DAG);
19814   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
19815   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
19816   case ISD::VASTART:            return LowerVASTART(Op, DAG);
19817   case ISD::VAARG:              return LowerVAARG(Op, DAG);
19818   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
19819   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19820   case ISD::INTRINSIC_VOID:
19821   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19822   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
19823   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
19824   case ISD::FRAME_TO_ARGS_OFFSET:
19825                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19826   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19827   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
19828   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
19829   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
19830   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
19831   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
19832   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
19833   case ISD::CTLZ:               return LowerCTLZ(Op, Subtarget, DAG);
19834   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19835   case ISD::CTTZ:
19836   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, DAG);
19837   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
19838   case ISD::UMUL_LOHI:
19839   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
19840   case ISD::ROTL:               return LowerRotate(Op, Subtarget, DAG);
19841   case ISD::SRA:
19842   case ISD::SRL:
19843   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
19844   case ISD::SADDO:
19845   case ISD::UADDO:
19846   case ISD::SSUBO:
19847   case ISD::USUBO:
19848   case ISD::SMULO:
19849   case ISD::UMULO:              return LowerXALUO(Op, DAG);
19850   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19851   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
19852   case ISD::ADDC:
19853   case ISD::ADDE:
19854   case ISD::SUBC:
19855   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19856   case ISD::ADD:                return LowerADD(Op, DAG);
19857   case ISD::SUB:                return LowerSUB(Op, DAG);
19858   case ISD::SMAX:
19859   case ISD::SMIN:
19860   case ISD::UMAX:
19861   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
19862   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
19863   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
19864   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
19865   case ISD::GC_TRANSITION_START:
19866                                 return LowerGC_TRANSITION_START(Op, DAG);
19867   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
19868   }
19869 }
19870
19871 /// ReplaceNodeResults - Replace a node with an illegal result type
19872 /// with a new node built out of custom code.
19873 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19874                                            SmallVectorImpl<SDValue>&Results,
19875                                            SelectionDAG &DAG) const {
19876   SDLoc dl(N);
19877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19878   switch (N->getOpcode()) {
19879   default:
19880     llvm_unreachable("Do not know how to custom type legalize this operation!");
19881   case X86ISD::AVG: {
19882     // Legalize types for X86ISD::AVG by expanding vectors.
19883     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19884
19885     auto InVT = N->getValueType(0);
19886     auto InVTSize = InVT.getSizeInBits();
19887     const unsigned RegSize =
19888         (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
19889     assert((!Subtarget->hasAVX512() || RegSize < 512) &&
19890            "512-bit vector requires AVX512");
19891     assert((!Subtarget->hasAVX2() || RegSize < 256) &&
19892            "256-bit vector requires AVX2");
19893
19894     auto ElemVT = InVT.getVectorElementType();
19895     auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
19896                                   RegSize / ElemVT.getSizeInBits());
19897     assert(RegSize % InVT.getSizeInBits() == 0);
19898     unsigned NumConcat = RegSize / InVT.getSizeInBits();
19899
19900     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
19901     Ops[0] = N->getOperand(0);
19902     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
19903     Ops[0] = N->getOperand(1);
19904     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
19905
19906     SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
19907     Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
19908                                   DAG.getIntPtrConstant(0, dl)));
19909     return;
19910   }
19911   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19912   case X86ISD::FMINC:
19913   case X86ISD::FMIN:
19914   case X86ISD::FMAXC:
19915   case X86ISD::FMAX: {
19916     EVT VT = N->getValueType(0);
19917     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
19918     SDValue UNDEF = DAG.getUNDEF(VT);
19919     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19920                               N->getOperand(0), UNDEF);
19921     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19922                               N->getOperand(1), UNDEF);
19923     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19924     return;
19925   }
19926   case ISD::SIGN_EXTEND_INREG:
19927   case ISD::ADDC:
19928   case ISD::ADDE:
19929   case ISD::SUBC:
19930   case ISD::SUBE:
19931     // We don't want to expand or promote these.
19932     return;
19933   case ISD::SDIV:
19934   case ISD::UDIV:
19935   case ISD::SREM:
19936   case ISD::UREM:
19937   case ISD::SDIVREM:
19938   case ISD::UDIVREM: {
19939     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19940     Results.push_back(V);
19941     return;
19942   }
19943   case ISD::FP_TO_SINT:
19944   case ISD::FP_TO_UINT: {
19945     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19946
19947     std::pair<SDValue,SDValue> Vals =
19948         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19949     SDValue FIST = Vals.first, StackSlot = Vals.second;
19950     if (FIST.getNode()) {
19951       EVT VT = N->getValueType(0);
19952       // Return a load from the stack slot.
19953       if (StackSlot.getNode())
19954         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19955                                       MachinePointerInfo(),
19956                                       false, false, false, 0));
19957       else
19958         Results.push_back(FIST);
19959     }
19960     return;
19961   }
19962   case ISD::UINT_TO_FP: {
19963     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19964     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19965         N->getValueType(0) != MVT::v2f32)
19966       return;
19967     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19968                                  N->getOperand(0));
19969     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19970                                      MVT::f64);
19971     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19972     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19973                              DAG.getBitcast(MVT::v2i64, VBias));
19974     Or = DAG.getBitcast(MVT::v2f64, Or);
19975     // TODO: Are there any fast-math-flags to propagate here?
19976     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19977     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19978     return;
19979   }
19980   case ISD::FP_ROUND: {
19981     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19982         return;
19983     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19984     Results.push_back(V);
19985     return;
19986   }
19987   case ISD::FP_EXTEND: {
19988     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19989     // No other ValueType for FP_EXTEND should reach this point.
19990     assert(N->getValueType(0) == MVT::v2f32 &&
19991            "Do not know how to legalize this Node");
19992     return;
19993   }
19994   case ISD::INTRINSIC_W_CHAIN: {
19995     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19996     switch (IntNo) {
19997     default : llvm_unreachable("Do not know how to custom type "
19998                                "legalize this intrinsic operation!");
19999     case Intrinsic::x86_rdtsc:
20000       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20001                                      Results);
20002     case Intrinsic::x86_rdtscp:
20003       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20004                                      Results);
20005     case Intrinsic::x86_rdpmc:
20006       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20007     }
20008   }
20009   case ISD::READCYCLECOUNTER: {
20010     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20011                                    Results);
20012   }
20013   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20014     EVT T = N->getValueType(0);
20015     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20016     bool Regs64bit = T == MVT::i128;
20017     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20018     SDValue cpInL, cpInH;
20019     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20020                         DAG.getConstant(0, dl, HalfT));
20021     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20022                         DAG.getConstant(1, dl, HalfT));
20023     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20024                              Regs64bit ? X86::RAX : X86::EAX,
20025                              cpInL, SDValue());
20026     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20027                              Regs64bit ? X86::RDX : X86::EDX,
20028                              cpInH, cpInL.getValue(1));
20029     SDValue swapInL, swapInH;
20030     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20031                           DAG.getConstant(0, dl, HalfT));
20032     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20033                           DAG.getConstant(1, dl, HalfT));
20034     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20035                                Regs64bit ? X86::RBX : X86::EBX,
20036                                swapInL, cpInH.getValue(1));
20037     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20038                                Regs64bit ? X86::RCX : X86::ECX,
20039                                swapInH, swapInL.getValue(1));
20040     SDValue Ops[] = { swapInH.getValue(0),
20041                       N->getOperand(1),
20042                       swapInH.getValue(1) };
20043     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20044     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20045     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20046                                   X86ISD::LCMPXCHG8_DAG;
20047     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20048     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20049                                         Regs64bit ? X86::RAX : X86::EAX,
20050                                         HalfT, Result.getValue(1));
20051     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20052                                         Regs64bit ? X86::RDX : X86::EDX,
20053                                         HalfT, cpOutL.getValue(2));
20054     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20055
20056     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20057                                         MVT::i32, cpOutH.getValue(2));
20058     SDValue Success =
20059         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20060                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20061     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20062
20063     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20064     Results.push_back(Success);
20065     Results.push_back(EFLAGS.getValue(1));
20066     return;
20067   }
20068   case ISD::ATOMIC_SWAP:
20069   case ISD::ATOMIC_LOAD_ADD:
20070   case ISD::ATOMIC_LOAD_SUB:
20071   case ISD::ATOMIC_LOAD_AND:
20072   case ISD::ATOMIC_LOAD_OR:
20073   case ISD::ATOMIC_LOAD_XOR:
20074   case ISD::ATOMIC_LOAD_NAND:
20075   case ISD::ATOMIC_LOAD_MIN:
20076   case ISD::ATOMIC_LOAD_MAX:
20077   case ISD::ATOMIC_LOAD_UMIN:
20078   case ISD::ATOMIC_LOAD_UMAX:
20079   case ISD::ATOMIC_LOAD: {
20080     // Delegate to generic TypeLegalization. Situations we can really handle
20081     // should have already been dealt with by AtomicExpandPass.cpp.
20082     break;
20083   }
20084   case ISD::BITCAST: {
20085     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20086     EVT DstVT = N->getValueType(0);
20087     EVT SrcVT = N->getOperand(0)->getValueType(0);
20088
20089     if (SrcVT != MVT::f64 ||
20090         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20091       return;
20092
20093     unsigned NumElts = DstVT.getVectorNumElements();
20094     EVT SVT = DstVT.getVectorElementType();
20095     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20096     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20097                                    MVT::v2f64, N->getOperand(0));
20098     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20099
20100     if (ExperimentalVectorWideningLegalization) {
20101       // If we are legalizing vectors by widening, we already have the desired
20102       // legal vector type, just return it.
20103       Results.push_back(ToVecInt);
20104       return;
20105     }
20106
20107     SmallVector<SDValue, 8> Elts;
20108     for (unsigned i = 0, e = NumElts; i != e; ++i)
20109       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20110                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
20111
20112     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20113   }
20114   }
20115 }
20116
20117 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20118   switch ((X86ISD::NodeType)Opcode) {
20119   case X86ISD::FIRST_NUMBER:       break;
20120   case X86ISD::BSF:                return "X86ISD::BSF";
20121   case X86ISD::BSR:                return "X86ISD::BSR";
20122   case X86ISD::SHLD:               return "X86ISD::SHLD";
20123   case X86ISD::SHRD:               return "X86ISD::SHRD";
20124   case X86ISD::FAND:               return "X86ISD::FAND";
20125   case X86ISD::FANDN:              return "X86ISD::FANDN";
20126   case X86ISD::FOR:                return "X86ISD::FOR";
20127   case X86ISD::FXOR:               return "X86ISD::FXOR";
20128   case X86ISD::FILD:               return "X86ISD::FILD";
20129   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
20130   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20131   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20132   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20133   case X86ISD::FLD:                return "X86ISD::FLD";
20134   case X86ISD::FST:                return "X86ISD::FST";
20135   case X86ISD::CALL:               return "X86ISD::CALL";
20136   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
20137   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
20138   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
20139   case X86ISD::BT:                 return "X86ISD::BT";
20140   case X86ISD::CMP:                return "X86ISD::CMP";
20141   case X86ISD::COMI:               return "X86ISD::COMI";
20142   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
20143   case X86ISD::CMPM:               return "X86ISD::CMPM";
20144   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
20145   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
20146   case X86ISD::SETCC:              return "X86ISD::SETCC";
20147   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
20148   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
20149   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
20150   case X86ISD::CMOV:               return "X86ISD::CMOV";
20151   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
20152   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
20153   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
20154   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
20155   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
20156   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
20157   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
20158   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
20159   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
20160   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
20161   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
20162   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
20163   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
20164   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
20165   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
20166   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
20167   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
20168   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
20169   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
20170   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
20171   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
20172   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
20173   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
20174   case X86ISD::HADD:               return "X86ISD::HADD";
20175   case X86ISD::HSUB:               return "X86ISD::HSUB";
20176   case X86ISD::FHADD:              return "X86ISD::FHADD";
20177   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
20178   case X86ISD::ABS:                return "X86ISD::ABS";
20179   case X86ISD::CONFLICT:           return "X86ISD::CONFLICT";
20180   case X86ISD::FMAX:               return "X86ISD::FMAX";
20181   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
20182   case X86ISD::FMIN:               return "X86ISD::FMIN";
20183   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
20184   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
20185   case X86ISD::FMINC:              return "X86ISD::FMINC";
20186   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
20187   case X86ISD::FRCP:               return "X86ISD::FRCP";
20188   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
20189   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
20190   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
20191   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
20192   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
20193   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
20194   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
20195   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
20196   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
20197   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
20198   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
20199   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
20200   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
20201   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
20202   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
20203   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
20204   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
20205   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
20206   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
20207   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
20208   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
20209   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
20210   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
20211   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
20212   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
20213   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
20214   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
20215   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
20216   case X86ISD::VSHL:               return "X86ISD::VSHL";
20217   case X86ISD::VSRL:               return "X86ISD::VSRL";
20218   case X86ISD::VSRA:               return "X86ISD::VSRA";
20219   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
20220   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
20221   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
20222   case X86ISD::CMPP:               return "X86ISD::CMPP";
20223   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
20224   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
20225   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
20226   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
20227   case X86ISD::ADD:                return "X86ISD::ADD";
20228   case X86ISD::SUB:                return "X86ISD::SUB";
20229   case X86ISD::ADC:                return "X86ISD::ADC";
20230   case X86ISD::SBB:                return "X86ISD::SBB";
20231   case X86ISD::SMUL:               return "X86ISD::SMUL";
20232   case X86ISD::UMUL:               return "X86ISD::UMUL";
20233   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
20234   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
20235   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20236   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20237   case X86ISD::INC:                return "X86ISD::INC";
20238   case X86ISD::DEC:                return "X86ISD::DEC";
20239   case X86ISD::OR:                 return "X86ISD::OR";
20240   case X86ISD::XOR:                return "X86ISD::XOR";
20241   case X86ISD::AND:                return "X86ISD::AND";
20242   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
20243   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
20244   case X86ISD::PTEST:              return "X86ISD::PTEST";
20245   case X86ISD::TESTP:              return "X86ISD::TESTP";
20246   case X86ISD::TESTM:              return "X86ISD::TESTM";
20247   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
20248   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
20249   case X86ISD::KTEST:              return "X86ISD::KTEST";
20250   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
20251   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
20252   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
20253   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
20254   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
20255   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
20256   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
20257   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
20258   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
20259   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
20260   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
20261   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
20262   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
20263   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
20264   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
20265   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
20266   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
20267   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
20268   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
20269   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
20270   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
20271   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
20272   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
20273   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
20274   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
20275   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
20276   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
20277   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
20278   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
20279   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
20280   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
20281   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
20282   case X86ISD::VPTERNLOG:          return "X86ISD::VPTERNLOG";
20283   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
20284   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
20285   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
20286   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
20287   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
20288   case X86ISD::DBPSADBW:           return "X86ISD::DBPSADBW";
20289   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20290   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
20291   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
20292   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
20293   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
20294   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
20295   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
20296   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
20297   case X86ISD::SAHF:               return "X86ISD::SAHF";
20298   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
20299   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
20300   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
20301   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
20302   case X86ISD::VPROT:              return "X86ISD::VPROT";
20303   case X86ISD::VPROTI:             return "X86ISD::VPROTI";
20304   case X86ISD::VPSHA:              return "X86ISD::VPSHA";
20305   case X86ISD::VPSHL:              return "X86ISD::VPSHL";
20306   case X86ISD::VPCOM:              return "X86ISD::VPCOM";
20307   case X86ISD::VPCOMU:             return "X86ISD::VPCOMU";
20308   case X86ISD::FMADD:              return "X86ISD::FMADD";
20309   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
20310   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
20311   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
20312   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
20313   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
20314   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
20315   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
20316   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
20317   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
20318   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
20319   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
20320   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
20321   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
20322   case X86ISD::VGETMANT:           return "X86ISD::VGETMANT";
20323   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
20324   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
20325   case X86ISD::XTEST:              return "X86ISD::XTEST";
20326   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
20327   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
20328   case X86ISD::SELECT:             return "X86ISD::SELECT";
20329   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
20330   case X86ISD::RCP28:              return "X86ISD::RCP28";
20331   case X86ISD::EXP2:               return "X86ISD::EXP2";
20332   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
20333   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
20334   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
20335   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
20336   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
20337   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
20338   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
20339   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
20340   case X86ISD::ADDS:               return "X86ISD::ADDS";
20341   case X86ISD::SUBS:               return "X86ISD::SUBS";
20342   case X86ISD::AVG:                return "X86ISD::AVG";
20343   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
20344   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
20345   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
20346   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
20347   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
20348   case X86ISD::VFPCLASS:           return "X86ISD::VFPCLASS";
20349   }
20350   return nullptr;
20351 }
20352
20353 // isLegalAddressingMode - Return true if the addressing mode represented
20354 // by AM is legal for this target, for a load/store of the specified type.
20355 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20356                                               const AddrMode &AM, Type *Ty,
20357                                               unsigned AS) const {
20358   // X86 supports extremely general addressing modes.
20359   CodeModel::Model M = getTargetMachine().getCodeModel();
20360   Reloc::Model R = getTargetMachine().getRelocationModel();
20361
20362   // X86 allows a sign-extended 32-bit immediate field as a displacement.
20363   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20364     return false;
20365
20366   if (AM.BaseGV) {
20367     unsigned GVFlags =
20368       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20369
20370     // If a reference to this global requires an extra load, we can't fold it.
20371     if (isGlobalStubReference(GVFlags))
20372       return false;
20373
20374     // If BaseGV requires a register for the PIC base, we cannot also have a
20375     // BaseReg specified.
20376     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20377       return false;
20378
20379     // If lower 4G is not available, then we must use rip-relative addressing.
20380     if ((M != CodeModel::Small || R != Reloc::Static) &&
20381         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20382       return false;
20383   }
20384
20385   switch (AM.Scale) {
20386   case 0:
20387   case 1:
20388   case 2:
20389   case 4:
20390   case 8:
20391     // These scales always work.
20392     break;
20393   case 3:
20394   case 5:
20395   case 9:
20396     // These scales are formed with basereg+scalereg.  Only accept if there is
20397     // no basereg yet.
20398     if (AM.HasBaseReg)
20399       return false;
20400     break;
20401   default:  // Other stuff never works.
20402     return false;
20403   }
20404
20405   return true;
20406 }
20407
20408 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20409   unsigned Bits = Ty->getScalarSizeInBits();
20410
20411   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20412   // particularly cheaper than those without.
20413   if (Bits == 8)
20414     return false;
20415
20416   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20417   // variable shifts just as cheap as scalar ones.
20418   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20419     return false;
20420
20421   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20422   // fully general vector.
20423   return true;
20424 }
20425
20426 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20427   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20428     return false;
20429   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20430   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20431   return NumBits1 > NumBits2;
20432 }
20433
20434 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20435   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20436     return false;
20437
20438   if (!isTypeLegal(EVT::getEVT(Ty1)))
20439     return false;
20440
20441   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20442
20443   // Assuming the caller doesn't have a zeroext or signext return parameter,
20444   // truncation all the way down to i1 is valid.
20445   return true;
20446 }
20447
20448 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20449   return isInt<32>(Imm);
20450 }
20451
20452 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20453   // Can also use sub to handle negated immediates.
20454   return isInt<32>(Imm);
20455 }
20456
20457 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20458   if (!VT1.isInteger() || !VT2.isInteger())
20459     return false;
20460   unsigned NumBits1 = VT1.getSizeInBits();
20461   unsigned NumBits2 = VT2.getSizeInBits();
20462   return NumBits1 > NumBits2;
20463 }
20464
20465 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20466   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20467   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20468 }
20469
20470 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20471   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20472   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20473 }
20474
20475 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20476   EVT VT1 = Val.getValueType();
20477   if (isZExtFree(VT1, VT2))
20478     return true;
20479
20480   if (Val.getOpcode() != ISD::LOAD)
20481     return false;
20482
20483   if (!VT1.isSimple() || !VT1.isInteger() ||
20484       !VT2.isSimple() || !VT2.isInteger())
20485     return false;
20486
20487   switch (VT1.getSimpleVT().SimpleTy) {
20488   default: break;
20489   case MVT::i8:
20490   case MVT::i16:
20491   case MVT::i32:
20492     // X86 has 8, 16, and 32-bit zero-extending loads.
20493     return true;
20494   }
20495
20496   return false;
20497 }
20498
20499 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20500
20501 bool
20502 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20503   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20504     return false;
20505
20506   VT = VT.getScalarType();
20507
20508   if (!VT.isSimple())
20509     return false;
20510
20511   switch (VT.getSimpleVT().SimpleTy) {
20512   case MVT::f32:
20513   case MVT::f64:
20514     return true;
20515   default:
20516     break;
20517   }
20518
20519   return false;
20520 }
20521
20522 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20523   // i16 instructions are longer (0x66 prefix) and potentially slower.
20524   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20525 }
20526
20527 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20528 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20529 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20530 /// are assumed to be legal.
20531 bool
20532 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20533                                       EVT VT) const {
20534   if (!VT.isSimple())
20535     return false;
20536
20537   // Not for i1 vectors
20538   if (VT.getSimpleVT().getScalarType() == MVT::i1)
20539     return false;
20540
20541   // Very little shuffling can be done for 64-bit vectors right now.
20542   if (VT.getSimpleVT().getSizeInBits() == 64)
20543     return false;
20544
20545   // We only care that the types being shuffled are legal. The lowering can
20546   // handle any possible shuffle mask that results.
20547   return isTypeLegal(VT.getSimpleVT());
20548 }
20549
20550 bool
20551 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20552                                           EVT VT) const {
20553   // Just delegate to the generic legality, clear masks aren't special.
20554   return isShuffleMaskLegal(Mask, VT);
20555 }
20556
20557 //===----------------------------------------------------------------------===//
20558 //                           X86 Scheduler Hooks
20559 //===----------------------------------------------------------------------===//
20560
20561 /// Utility function to emit xbegin specifying the start of an RTM region.
20562 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20563                                      const TargetInstrInfo *TII) {
20564   DebugLoc DL = MI->getDebugLoc();
20565
20566   const BasicBlock *BB = MBB->getBasicBlock();
20567   MachineFunction::iterator I = ++MBB->getIterator();
20568
20569   // For the v = xbegin(), we generate
20570   //
20571   // thisMBB:
20572   //  xbegin sinkMBB
20573   //
20574   // mainMBB:
20575   //  eax = -1
20576   //
20577   // sinkMBB:
20578   //  v = eax
20579
20580   MachineBasicBlock *thisMBB = MBB;
20581   MachineFunction *MF = MBB->getParent();
20582   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20583   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20584   MF->insert(I, mainMBB);
20585   MF->insert(I, sinkMBB);
20586
20587   // Transfer the remainder of BB and its successor edges to sinkMBB.
20588   sinkMBB->splice(sinkMBB->begin(), MBB,
20589                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20590   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20591
20592   // thisMBB:
20593   //  xbegin sinkMBB
20594   //  # fallthrough to mainMBB
20595   //  # abortion to sinkMBB
20596   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20597   thisMBB->addSuccessor(mainMBB);
20598   thisMBB->addSuccessor(sinkMBB);
20599
20600   // mainMBB:
20601   //  EAX = -1
20602   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20603   mainMBB->addSuccessor(sinkMBB);
20604
20605   // sinkMBB:
20606   // EAX is live into the sinkMBB
20607   sinkMBB->addLiveIn(X86::EAX);
20608   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20609           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20610     .addReg(X86::EAX);
20611
20612   MI->eraseFromParent();
20613   return sinkMBB;
20614 }
20615
20616 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20617 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20618 // in the .td file.
20619 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20620                                        const TargetInstrInfo *TII) {
20621   unsigned Opc;
20622   switch (MI->getOpcode()) {
20623   default: llvm_unreachable("illegal opcode!");
20624   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
20625   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20626   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
20627   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20628   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
20629   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20630   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
20631   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20632   }
20633
20634   DebugLoc dl = MI->getDebugLoc();
20635   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20636
20637   unsigned NumArgs = MI->getNumOperands();
20638   for (unsigned i = 1; i < NumArgs; ++i) {
20639     MachineOperand &Op = MI->getOperand(i);
20640     if (!(Op.isReg() && Op.isImplicit()))
20641       MIB.addOperand(Op);
20642   }
20643   if (MI->hasOneMemOperand())
20644     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20645
20646   BuildMI(*BB, MI, dl,
20647     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20648     .addReg(X86::XMM0);
20649
20650   MI->eraseFromParent();
20651   return BB;
20652 }
20653
20654 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20655 // defs in an instruction pattern
20656 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20657                                        const TargetInstrInfo *TII) {
20658   unsigned Opc;
20659   switch (MI->getOpcode()) {
20660   default: llvm_unreachable("illegal opcode!");
20661   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
20662   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20663   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
20664   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20665   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
20666   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20667   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
20668   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20669   }
20670
20671   DebugLoc dl = MI->getDebugLoc();
20672   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20673
20674   unsigned NumArgs = MI->getNumOperands(); // remove the results
20675   for (unsigned i = 1; i < NumArgs; ++i) {
20676     MachineOperand &Op = MI->getOperand(i);
20677     if (!(Op.isReg() && Op.isImplicit()))
20678       MIB.addOperand(Op);
20679   }
20680   if (MI->hasOneMemOperand())
20681     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20682
20683   BuildMI(*BB, MI, dl,
20684     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20685     .addReg(X86::ECX);
20686
20687   MI->eraseFromParent();
20688   return BB;
20689 }
20690
20691 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20692                                       const X86Subtarget *Subtarget) {
20693   DebugLoc dl = MI->getDebugLoc();
20694   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20695   // Address into RAX/EAX, other two args into ECX, EDX.
20696   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20697   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20698   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20699   for (int i = 0; i < X86::AddrNumOperands; ++i)
20700     MIB.addOperand(MI->getOperand(i));
20701
20702   unsigned ValOps = X86::AddrNumOperands;
20703   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20704     .addReg(MI->getOperand(ValOps).getReg());
20705   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20706     .addReg(MI->getOperand(ValOps+1).getReg());
20707
20708   // The instruction doesn't actually take any operands though.
20709   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20710
20711   MI->eraseFromParent(); // The pseudo is gone now.
20712   return BB;
20713 }
20714
20715 MachineBasicBlock *
20716 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20717                                                  MachineBasicBlock *MBB) const {
20718   // Emit va_arg instruction on X86-64.
20719
20720   // Operands to this pseudo-instruction:
20721   // 0  ) Output        : destination address (reg)
20722   // 1-5) Input         : va_list address (addr, i64mem)
20723   // 6  ) ArgSize       : Size (in bytes) of vararg type
20724   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20725   // 8  ) Align         : Alignment of type
20726   // 9  ) EFLAGS (implicit-def)
20727
20728   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20729   static_assert(X86::AddrNumOperands == 5,
20730                 "VAARG_64 assumes 5 address operands");
20731
20732   unsigned DestReg = MI->getOperand(0).getReg();
20733   MachineOperand &Base = MI->getOperand(1);
20734   MachineOperand &Scale = MI->getOperand(2);
20735   MachineOperand &Index = MI->getOperand(3);
20736   MachineOperand &Disp = MI->getOperand(4);
20737   MachineOperand &Segment = MI->getOperand(5);
20738   unsigned ArgSize = MI->getOperand(6).getImm();
20739   unsigned ArgMode = MI->getOperand(7).getImm();
20740   unsigned Align = MI->getOperand(8).getImm();
20741
20742   // Memory Reference
20743   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20744   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20745   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20746
20747   // Machine Information
20748   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20749   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20750   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20751   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20752   DebugLoc DL = MI->getDebugLoc();
20753
20754   // struct va_list {
20755   //   i32   gp_offset
20756   //   i32   fp_offset
20757   //   i64   overflow_area (address)
20758   //   i64   reg_save_area (address)
20759   // }
20760   // sizeof(va_list) = 24
20761   // alignment(va_list) = 8
20762
20763   unsigned TotalNumIntRegs = 6;
20764   unsigned TotalNumXMMRegs = 8;
20765   bool UseGPOffset = (ArgMode == 1);
20766   bool UseFPOffset = (ArgMode == 2);
20767   unsigned MaxOffset = TotalNumIntRegs * 8 +
20768                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20769
20770   /* Align ArgSize to a multiple of 8 */
20771   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20772   bool NeedsAlign = (Align > 8);
20773
20774   MachineBasicBlock *thisMBB = MBB;
20775   MachineBasicBlock *overflowMBB;
20776   MachineBasicBlock *offsetMBB;
20777   MachineBasicBlock *endMBB;
20778
20779   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
20780   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
20781   unsigned OffsetReg = 0;
20782
20783   if (!UseGPOffset && !UseFPOffset) {
20784     // If we only pull from the overflow region, we don't create a branch.
20785     // We don't need to alter control flow.
20786     OffsetDestReg = 0; // unused
20787     OverflowDestReg = DestReg;
20788
20789     offsetMBB = nullptr;
20790     overflowMBB = thisMBB;
20791     endMBB = thisMBB;
20792   } else {
20793     // First emit code to check if gp_offset (or fp_offset) is below the bound.
20794     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20795     // If not, pull from overflow_area. (branch to overflowMBB)
20796     //
20797     //       thisMBB
20798     //         |     .
20799     //         |        .
20800     //     offsetMBB   overflowMBB
20801     //         |        .
20802     //         |     .
20803     //        endMBB
20804
20805     // Registers for the PHI in endMBB
20806     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20807     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20808
20809     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20810     MachineFunction *MF = MBB->getParent();
20811     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20812     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20813     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20814
20815     MachineFunction::iterator MBBIter = ++MBB->getIterator();
20816
20817     // Insert the new basic blocks
20818     MF->insert(MBBIter, offsetMBB);
20819     MF->insert(MBBIter, overflowMBB);
20820     MF->insert(MBBIter, endMBB);
20821
20822     // Transfer the remainder of MBB and its successor edges to endMBB.
20823     endMBB->splice(endMBB->begin(), thisMBB,
20824                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20825     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20826
20827     // Make offsetMBB and overflowMBB successors of thisMBB
20828     thisMBB->addSuccessor(offsetMBB);
20829     thisMBB->addSuccessor(overflowMBB);
20830
20831     // endMBB is a successor of both offsetMBB and overflowMBB
20832     offsetMBB->addSuccessor(endMBB);
20833     overflowMBB->addSuccessor(endMBB);
20834
20835     // Load the offset value into a register
20836     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20837     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20838       .addOperand(Base)
20839       .addOperand(Scale)
20840       .addOperand(Index)
20841       .addDisp(Disp, UseFPOffset ? 4 : 0)
20842       .addOperand(Segment)
20843       .setMemRefs(MMOBegin, MMOEnd);
20844
20845     // Check if there is enough room left to pull this argument.
20846     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20847       .addReg(OffsetReg)
20848       .addImm(MaxOffset + 8 - ArgSizeA8);
20849
20850     // Branch to "overflowMBB" if offset >= max
20851     // Fall through to "offsetMBB" otherwise
20852     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20853       .addMBB(overflowMBB);
20854   }
20855
20856   // In offsetMBB, emit code to use the reg_save_area.
20857   if (offsetMBB) {
20858     assert(OffsetReg != 0);
20859
20860     // Read the reg_save_area address.
20861     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20862     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20863       .addOperand(Base)
20864       .addOperand(Scale)
20865       .addOperand(Index)
20866       .addDisp(Disp, 16)
20867       .addOperand(Segment)
20868       .setMemRefs(MMOBegin, MMOEnd);
20869
20870     // Zero-extend the offset
20871     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20872       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20873         .addImm(0)
20874         .addReg(OffsetReg)
20875         .addImm(X86::sub_32bit);
20876
20877     // Add the offset to the reg_save_area to get the final address.
20878     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20879       .addReg(OffsetReg64)
20880       .addReg(RegSaveReg);
20881
20882     // Compute the offset for the next argument
20883     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20884     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20885       .addReg(OffsetReg)
20886       .addImm(UseFPOffset ? 16 : 8);
20887
20888     // Store it back into the va_list.
20889     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20890       .addOperand(Base)
20891       .addOperand(Scale)
20892       .addOperand(Index)
20893       .addDisp(Disp, UseFPOffset ? 4 : 0)
20894       .addOperand(Segment)
20895       .addReg(NextOffsetReg)
20896       .setMemRefs(MMOBegin, MMOEnd);
20897
20898     // Jump to endMBB
20899     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20900       .addMBB(endMBB);
20901   }
20902
20903   //
20904   // Emit code to use overflow area
20905   //
20906
20907   // Load the overflow_area address into a register.
20908   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20909   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20910     .addOperand(Base)
20911     .addOperand(Scale)
20912     .addOperand(Index)
20913     .addDisp(Disp, 8)
20914     .addOperand(Segment)
20915     .setMemRefs(MMOBegin, MMOEnd);
20916
20917   // If we need to align it, do so. Otherwise, just copy the address
20918   // to OverflowDestReg.
20919   if (NeedsAlign) {
20920     // Align the overflow address
20921     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20922     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20923
20924     // aligned_addr = (addr + (align-1)) & ~(align-1)
20925     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20926       .addReg(OverflowAddrReg)
20927       .addImm(Align-1);
20928
20929     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20930       .addReg(TmpReg)
20931       .addImm(~(uint64_t)(Align-1));
20932   } else {
20933     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20934       .addReg(OverflowAddrReg);
20935   }
20936
20937   // Compute the next overflow address after this argument.
20938   // (the overflow address should be kept 8-byte aligned)
20939   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20940   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20941     .addReg(OverflowDestReg)
20942     .addImm(ArgSizeA8);
20943
20944   // Store the new overflow address.
20945   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20946     .addOperand(Base)
20947     .addOperand(Scale)
20948     .addOperand(Index)
20949     .addDisp(Disp, 8)
20950     .addOperand(Segment)
20951     .addReg(NextAddrReg)
20952     .setMemRefs(MMOBegin, MMOEnd);
20953
20954   // If we branched, emit the PHI to the front of endMBB.
20955   if (offsetMBB) {
20956     BuildMI(*endMBB, endMBB->begin(), DL,
20957             TII->get(X86::PHI), DestReg)
20958       .addReg(OffsetDestReg).addMBB(offsetMBB)
20959       .addReg(OverflowDestReg).addMBB(overflowMBB);
20960   }
20961
20962   // Erase the pseudo instruction
20963   MI->eraseFromParent();
20964
20965   return endMBB;
20966 }
20967
20968 MachineBasicBlock *
20969 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20970                                                  MachineInstr *MI,
20971                                                  MachineBasicBlock *MBB) const {
20972   // Emit code to save XMM registers to the stack. The ABI says that the
20973   // number of registers to save is given in %al, so it's theoretically
20974   // possible to do an indirect jump trick to avoid saving all of them,
20975   // however this code takes a simpler approach and just executes all
20976   // of the stores if %al is non-zero. It's less code, and it's probably
20977   // easier on the hardware branch predictor, and stores aren't all that
20978   // expensive anyway.
20979
20980   // Create the new basic blocks. One block contains all the XMM stores,
20981   // and one block is the final destination regardless of whether any
20982   // stores were performed.
20983   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20984   MachineFunction *F = MBB->getParent();
20985   MachineFunction::iterator MBBIter = ++MBB->getIterator();
20986   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20987   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20988   F->insert(MBBIter, XMMSaveMBB);
20989   F->insert(MBBIter, EndMBB);
20990
20991   // Transfer the remainder of MBB and its successor edges to EndMBB.
20992   EndMBB->splice(EndMBB->begin(), MBB,
20993                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20994   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20995
20996   // The original block will now fall through to the XMM save block.
20997   MBB->addSuccessor(XMMSaveMBB);
20998   // The XMMSaveMBB will fall through to the end block.
20999   XMMSaveMBB->addSuccessor(EndMBB);
21000
21001   // Now add the instructions.
21002   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21003   DebugLoc DL = MI->getDebugLoc();
21004
21005   unsigned CountReg = MI->getOperand(0).getReg();
21006   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21007   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21008
21009   if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21010     // If %al is 0, branch around the XMM save block.
21011     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21012     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21013     MBB->addSuccessor(EndMBB);
21014   }
21015
21016   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21017   // that was just emitted, but clearly shouldn't be "saved".
21018   assert((MI->getNumOperands() <= 3 ||
21019           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21020           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21021          && "Expected last argument to be EFLAGS");
21022   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21023   // In the XMM save block, save all the XMM argument registers.
21024   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21025     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21026     MachineMemOperand *MMO = F->getMachineMemOperand(
21027         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21028         MachineMemOperand::MOStore,
21029         /*Size=*/16, /*Align=*/16);
21030     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21031       .addFrameIndex(RegSaveFrameIndex)
21032       .addImm(/*Scale=*/1)
21033       .addReg(/*IndexReg=*/0)
21034       .addImm(/*Disp=*/Offset)
21035       .addReg(/*Segment=*/0)
21036       .addReg(MI->getOperand(i).getReg())
21037       .addMemOperand(MMO);
21038   }
21039
21040   MI->eraseFromParent();   // The pseudo instruction is gone now.
21041
21042   return EndMBB;
21043 }
21044
21045 // The EFLAGS operand of SelectItr might be missing a kill marker
21046 // because there were multiple uses of EFLAGS, and ISel didn't know
21047 // which to mark. Figure out whether SelectItr should have had a
21048 // kill marker, and set it if it should. Returns the correct kill
21049 // marker value.
21050 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21051                                      MachineBasicBlock* BB,
21052                                      const TargetRegisterInfo* TRI) {
21053   // Scan forward through BB for a use/def of EFLAGS.
21054   MachineBasicBlock::iterator miI(std::next(SelectItr));
21055   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21056     const MachineInstr& mi = *miI;
21057     if (mi.readsRegister(X86::EFLAGS))
21058       return false;
21059     if (mi.definesRegister(X86::EFLAGS))
21060       break; // Should have kill-flag - update below.
21061   }
21062
21063   // If we hit the end of the block, check whether EFLAGS is live into a
21064   // successor.
21065   if (miI == BB->end()) {
21066     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21067                                           sEnd = BB->succ_end();
21068          sItr != sEnd; ++sItr) {
21069       MachineBasicBlock* succ = *sItr;
21070       if (succ->isLiveIn(X86::EFLAGS))
21071         return false;
21072     }
21073   }
21074
21075   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21076   // out. SelectMI should have a kill flag on EFLAGS.
21077   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21078   return true;
21079 }
21080
21081 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21082 // together with other CMOV pseudo-opcodes into a single basic-block with
21083 // conditional jump around it.
21084 static bool isCMOVPseudo(MachineInstr *MI) {
21085   switch (MI->getOpcode()) {
21086   case X86::CMOV_FR32:
21087   case X86::CMOV_FR64:
21088   case X86::CMOV_GR8:
21089   case X86::CMOV_GR16:
21090   case X86::CMOV_GR32:
21091   case X86::CMOV_RFP32:
21092   case X86::CMOV_RFP64:
21093   case X86::CMOV_RFP80:
21094   case X86::CMOV_V2F64:
21095   case X86::CMOV_V2I64:
21096   case X86::CMOV_V4F32:
21097   case X86::CMOV_V4F64:
21098   case X86::CMOV_V4I64:
21099   case X86::CMOV_V16F32:
21100   case X86::CMOV_V8F32:
21101   case X86::CMOV_V8F64:
21102   case X86::CMOV_V8I64:
21103   case X86::CMOV_V8I1:
21104   case X86::CMOV_V16I1:
21105   case X86::CMOV_V32I1:
21106   case X86::CMOV_V64I1:
21107     return true;
21108
21109   default:
21110     return false;
21111   }
21112 }
21113
21114 MachineBasicBlock *
21115 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21116                                      MachineBasicBlock *BB) const {
21117   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21118   DebugLoc DL = MI->getDebugLoc();
21119
21120   // To "insert" a SELECT_CC instruction, we actually have to insert the
21121   // diamond control-flow pattern.  The incoming instruction knows the
21122   // destination vreg to set, the condition code register to branch on, the
21123   // true/false values to select between, and a branch opcode to use.
21124   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21125   MachineFunction::iterator It = ++BB->getIterator();
21126
21127   //  thisMBB:
21128   //  ...
21129   //   TrueVal = ...
21130   //   cmpTY ccX, r1, r2
21131   //   bCC copy1MBB
21132   //   fallthrough --> copy0MBB
21133   MachineBasicBlock *thisMBB = BB;
21134   MachineFunction *F = BB->getParent();
21135
21136   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21137   // as described above, by inserting a BB, and then making a PHI at the join
21138   // point to select the true and false operands of the CMOV in the PHI.
21139   //
21140   // The code also handles two different cases of multiple CMOV opcodes
21141   // in a row.
21142   //
21143   // Case 1:
21144   // In this case, there are multiple CMOVs in a row, all which are based on
21145   // the same condition setting (or the exact opposite condition setting).
21146   // In this case we can lower all the CMOVs using a single inserted BB, and
21147   // then make a number of PHIs at the join point to model the CMOVs. The only
21148   // trickiness here, is that in a case like:
21149   //
21150   // t2 = CMOV cond1 t1, f1
21151   // t3 = CMOV cond1 t2, f2
21152   //
21153   // when rewriting this into PHIs, we have to perform some renaming on the
21154   // temps since you cannot have a PHI operand refer to a PHI result earlier
21155   // in the same block.  The "simple" but wrong lowering would be:
21156   //
21157   // t2 = PHI t1(BB1), f1(BB2)
21158   // t3 = PHI t2(BB1), f2(BB2)
21159   //
21160   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21161   // renaming is to note that on the path through BB1, t2 is really just a
21162   // copy of t1, and do that renaming, properly generating:
21163   //
21164   // t2 = PHI t1(BB1), f1(BB2)
21165   // t3 = PHI t1(BB1), f2(BB2)
21166   //
21167   // Case 2, we lower cascaded CMOVs such as
21168   //
21169   //   (CMOV (CMOV F, T, cc1), T, cc2)
21170   //
21171   // to two successives branches.  For that, we look for another CMOV as the
21172   // following instruction.
21173   //
21174   // Without this, we would add a PHI between the two jumps, which ends up
21175   // creating a few copies all around. For instance, for
21176   //
21177   //    (sitofp (zext (fcmp une)))
21178   //
21179   // we would generate:
21180   //
21181   //         ucomiss %xmm1, %xmm0
21182   //         movss  <1.0f>, %xmm0
21183   //         movaps  %xmm0, %xmm1
21184   //         jne     .LBB5_2
21185   //         xorps   %xmm1, %xmm1
21186   // .LBB5_2:
21187   //         jp      .LBB5_4
21188   //         movaps  %xmm1, %xmm0
21189   // .LBB5_4:
21190   //         retq
21191   //
21192   // because this custom-inserter would have generated:
21193   //
21194   //   A
21195   //   | \
21196   //   |  B
21197   //   | /
21198   //   C
21199   //   | \
21200   //   |  D
21201   //   | /
21202   //   E
21203   //
21204   // A: X = ...; Y = ...
21205   // B: empty
21206   // C: Z = PHI [X, A], [Y, B]
21207   // D: empty
21208   // E: PHI [X, C], [Z, D]
21209   //
21210   // If we lower both CMOVs in a single step, we can instead generate:
21211   //
21212   //   A
21213   //   | \
21214   //   |  C
21215   //   | /|
21216   //   |/ |
21217   //   |  |
21218   //   |  D
21219   //   | /
21220   //   E
21221   //
21222   // A: X = ...; Y = ...
21223   // D: empty
21224   // E: PHI [X, A], [X, C], [Y, D]
21225   //
21226   // Which, in our sitofp/fcmp example, gives us something like:
21227   //
21228   //         ucomiss %xmm1, %xmm0
21229   //         movss  <1.0f>, %xmm0
21230   //         jne     .LBB5_4
21231   //         jp      .LBB5_4
21232   //         xorps   %xmm0, %xmm0
21233   // .LBB5_4:
21234   //         retq
21235   //
21236   MachineInstr *CascadedCMOV = nullptr;
21237   MachineInstr *LastCMOV = MI;
21238   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21239   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21240   MachineBasicBlock::iterator NextMIIt =
21241       std::next(MachineBasicBlock::iterator(MI));
21242
21243   // Check for case 1, where there are multiple CMOVs with the same condition
21244   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
21245   // number of jumps the most.
21246
21247   if (isCMOVPseudo(MI)) {
21248     // See if we have a string of CMOVS with the same condition.
21249     while (NextMIIt != BB->end() &&
21250            isCMOVPseudo(NextMIIt) &&
21251            (NextMIIt->getOperand(3).getImm() == CC ||
21252             NextMIIt->getOperand(3).getImm() == OppCC)) {
21253       LastCMOV = &*NextMIIt;
21254       ++NextMIIt;
21255     }
21256   }
21257
21258   // This checks for case 2, but only do this if we didn't already find
21259   // case 1, as indicated by LastCMOV == MI.
21260   if (LastCMOV == MI &&
21261       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21262       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21263       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21264     CascadedCMOV = &*NextMIIt;
21265   }
21266
21267   MachineBasicBlock *jcc1MBB = nullptr;
21268
21269   // If we have a cascaded CMOV, we lower it to two successive branches to
21270   // the same block.  EFLAGS is used by both, so mark it as live in the second.
21271   if (CascadedCMOV) {
21272     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21273     F->insert(It, jcc1MBB);
21274     jcc1MBB->addLiveIn(X86::EFLAGS);
21275   }
21276
21277   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21278   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21279   F->insert(It, copy0MBB);
21280   F->insert(It, sinkMBB);
21281
21282   // If the EFLAGS register isn't dead in the terminator, then claim that it's
21283   // live into the sink and copy blocks.
21284   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21285
21286   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21287   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21288       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21289     copy0MBB->addLiveIn(X86::EFLAGS);
21290     sinkMBB->addLiveIn(X86::EFLAGS);
21291   }
21292
21293   // Transfer the remainder of BB and its successor edges to sinkMBB.
21294   sinkMBB->splice(sinkMBB->begin(), BB,
21295                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21296   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21297
21298   // Add the true and fallthrough blocks as its successors.
21299   if (CascadedCMOV) {
21300     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21301     BB->addSuccessor(jcc1MBB);
21302
21303     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21304     // jump to the sinkMBB.
21305     jcc1MBB->addSuccessor(copy0MBB);
21306     jcc1MBB->addSuccessor(sinkMBB);
21307   } else {
21308     BB->addSuccessor(copy0MBB);
21309   }
21310
21311   // The true block target of the first (or only) branch is always sinkMBB.
21312   BB->addSuccessor(sinkMBB);
21313
21314   // Create the conditional branch instruction.
21315   unsigned Opc = X86::GetCondBranchFromCond(CC);
21316   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21317
21318   if (CascadedCMOV) {
21319     unsigned Opc2 = X86::GetCondBranchFromCond(
21320         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21321     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21322   }
21323
21324   //  copy0MBB:
21325   //   %FalseValue = ...
21326   //   # fallthrough to sinkMBB
21327   copy0MBB->addSuccessor(sinkMBB);
21328
21329   //  sinkMBB:
21330   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21331   //  ...
21332   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21333   MachineBasicBlock::iterator MIItEnd =
21334     std::next(MachineBasicBlock::iterator(LastCMOV));
21335   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21336   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21337   MachineInstrBuilder MIB;
21338
21339   // As we are creating the PHIs, we have to be careful if there is more than
21340   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
21341   // PHIs have to reference the individual true/false inputs from earlier PHIs.
21342   // That also means that PHI construction must work forward from earlier to
21343   // later, and that the code must maintain a mapping from earlier PHI's
21344   // destination registers, and the registers that went into the PHI.
21345
21346   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21347     unsigned DestReg = MIIt->getOperand(0).getReg();
21348     unsigned Op1Reg = MIIt->getOperand(1).getReg();
21349     unsigned Op2Reg = MIIt->getOperand(2).getReg();
21350
21351     // If this CMOV we are generating is the opposite condition from
21352     // the jump we generated, then we have to swap the operands for the
21353     // PHI that is going to be generated.
21354     if (MIIt->getOperand(3).getImm() == OppCC)
21355         std::swap(Op1Reg, Op2Reg);
21356
21357     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21358       Op1Reg = RegRewriteTable[Op1Reg].first;
21359
21360     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21361       Op2Reg = RegRewriteTable[Op2Reg].second;
21362
21363     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21364                   TII->get(X86::PHI), DestReg)
21365           .addReg(Op1Reg).addMBB(copy0MBB)
21366           .addReg(Op2Reg).addMBB(thisMBB);
21367
21368     // Add this PHI to the rewrite table.
21369     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21370   }
21371
21372   // If we have a cascaded CMOV, the second Jcc provides the same incoming
21373   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21374   if (CascadedCMOV) {
21375     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21376     // Copy the PHI result to the register defined by the second CMOV.
21377     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21378             DL, TII->get(TargetOpcode::COPY),
21379             CascadedCMOV->getOperand(0).getReg())
21380         .addReg(MI->getOperand(0).getReg());
21381     CascadedCMOV->eraseFromParent();
21382   }
21383
21384   // Now remove the CMOV(s).
21385   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21386     (MIIt++)->eraseFromParent();
21387
21388   return sinkMBB;
21389 }
21390
21391 MachineBasicBlock *
21392 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21393                                        MachineBasicBlock *BB) const {
21394   // Combine the following atomic floating-point modification pattern:
21395   //   a.store(reg OP a.load(acquire), release)
21396   // Transform them into:
21397   //   OPss (%gpr), %xmm
21398   //   movss %xmm, (%gpr)
21399   // Or sd equivalent for 64-bit operations.
21400   unsigned MOp, FOp;
21401   switch (MI->getOpcode()) {
21402   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21403   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21404   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21405   }
21406   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21407   DebugLoc DL = MI->getDebugLoc();
21408   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21409   MachineOperand MSrc = MI->getOperand(0);
21410   unsigned VSrc = MI->getOperand(5).getReg();
21411   const MachineOperand &Disp = MI->getOperand(3);
21412   MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21413   bool hasDisp = Disp.isGlobal() || Disp.isImm();
21414   if (hasDisp && MSrc.isReg())
21415     MSrc.setIsKill(false);
21416   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21417                                 .addOperand(/*Base=*/MSrc)
21418                                 .addImm(/*Scale=*/1)
21419                                 .addReg(/*Index=*/0)
21420                                 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21421                                 .addReg(0);
21422   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21423                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21424                           .addReg(VSrc)
21425                           .addOperand(/*Base=*/MSrc)
21426                           .addImm(/*Scale=*/1)
21427                           .addReg(/*Index=*/0)
21428                           .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21429                           .addReg(/*Segment=*/0);
21430   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21431   MI->eraseFromParent(); // The pseudo instruction is gone now.
21432   return BB;
21433 }
21434
21435 MachineBasicBlock *
21436 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21437                                         MachineBasicBlock *BB) const {
21438   MachineFunction *MF = BB->getParent();
21439   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21440   DebugLoc DL = MI->getDebugLoc();
21441   const BasicBlock *LLVM_BB = BB->getBasicBlock();
21442
21443   assert(MF->shouldSplitStack());
21444
21445   const bool Is64Bit = Subtarget->is64Bit();
21446   const bool IsLP64 = Subtarget->isTarget64BitLP64();
21447
21448   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21449   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21450
21451   // BB:
21452   //  ... [Till the alloca]
21453   // If stacklet is not large enough, jump to mallocMBB
21454   //
21455   // bumpMBB:
21456   //  Allocate by subtracting from RSP
21457   //  Jump to continueMBB
21458   //
21459   // mallocMBB:
21460   //  Allocate by call to runtime
21461   //
21462   // continueMBB:
21463   //  ...
21464   //  [rest of original BB]
21465   //
21466
21467   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21468   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21469   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21470
21471   MachineRegisterInfo &MRI = MF->getRegInfo();
21472   const TargetRegisterClass *AddrRegClass =
21473       getRegClassFor(getPointerTy(MF->getDataLayout()));
21474
21475   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21476     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21477     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21478     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21479     sizeVReg = MI->getOperand(1).getReg(),
21480     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21481
21482   MachineFunction::iterator MBBIter = ++BB->getIterator();
21483
21484   MF->insert(MBBIter, bumpMBB);
21485   MF->insert(MBBIter, mallocMBB);
21486   MF->insert(MBBIter, continueMBB);
21487
21488   continueMBB->splice(continueMBB->begin(), BB,
21489                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
21490   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21491
21492   // Add code to the main basic block to check if the stack limit has been hit,
21493   // and if so, jump to mallocMBB otherwise to bumpMBB.
21494   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21495   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21496     .addReg(tmpSPVReg).addReg(sizeVReg);
21497   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21498     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21499     .addReg(SPLimitVReg);
21500   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21501
21502   // bumpMBB simply decreases the stack pointer, since we know the current
21503   // stacklet has enough space.
21504   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21505     .addReg(SPLimitVReg);
21506   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21507     .addReg(SPLimitVReg);
21508   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21509
21510   // Calls into a routine in libgcc to allocate more space from the heap.
21511   const uint32_t *RegMask =
21512       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21513   if (IsLP64) {
21514     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21515       .addReg(sizeVReg);
21516     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21517       .addExternalSymbol("__morestack_allocate_stack_space")
21518       .addRegMask(RegMask)
21519       .addReg(X86::RDI, RegState::Implicit)
21520       .addReg(X86::RAX, RegState::ImplicitDefine);
21521   } else if (Is64Bit) {
21522     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21523       .addReg(sizeVReg);
21524     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21525       .addExternalSymbol("__morestack_allocate_stack_space")
21526       .addRegMask(RegMask)
21527       .addReg(X86::EDI, RegState::Implicit)
21528       .addReg(X86::EAX, RegState::ImplicitDefine);
21529   } else {
21530     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21531       .addImm(12);
21532     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21533     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21534       .addExternalSymbol("__morestack_allocate_stack_space")
21535       .addRegMask(RegMask)
21536       .addReg(X86::EAX, RegState::ImplicitDefine);
21537   }
21538
21539   if (!Is64Bit)
21540     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21541       .addImm(16);
21542
21543   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21544     .addReg(IsLP64 ? X86::RAX : X86::EAX);
21545   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21546
21547   // Set up the CFG correctly.
21548   BB->addSuccessor(bumpMBB);
21549   BB->addSuccessor(mallocMBB);
21550   mallocMBB->addSuccessor(continueMBB);
21551   bumpMBB->addSuccessor(continueMBB);
21552
21553   // Take care of the PHI nodes.
21554   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21555           MI->getOperand(0).getReg())
21556     .addReg(mallocPtrVReg).addMBB(mallocMBB)
21557     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21558
21559   // Delete the original pseudo instruction.
21560   MI->eraseFromParent();
21561
21562   // And we're done.
21563   return continueMBB;
21564 }
21565
21566 MachineBasicBlock *
21567 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21568                                         MachineBasicBlock *BB) const {
21569   assert(!Subtarget->isTargetMachO());
21570   DebugLoc DL = MI->getDebugLoc();
21571   MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
21572       *BB->getParent(), *BB, MI, DL, false);
21573   MachineBasicBlock *ResumeBB = ResumeMI->getParent();
21574   MI->eraseFromParent(); // The pseudo instruction is gone now.
21575   return ResumeBB;
21576 }
21577
21578 MachineBasicBlock *
21579 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
21580                                        MachineBasicBlock *BB) const {
21581   MachineFunction *MF = BB->getParent();
21582   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21583   MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
21584   DebugLoc DL = MI->getDebugLoc();
21585
21586   assert(!isAsynchronousEHPersonality(
21587              classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
21588          "SEH does not use catchret!");
21589
21590   // Only 32-bit EH needs to worry about manually restoring stack pointers.
21591   if (!Subtarget->is32Bit())
21592     return BB;
21593
21594   // C++ EH creates a new target block to hold the restore code, and wires up
21595   // the new block to the return destination with a normal JMP_4.
21596   MachineBasicBlock *RestoreMBB =
21597       MF->CreateMachineBasicBlock(BB->getBasicBlock());
21598   assert(BB->succ_size() == 1);
21599   MF->insert(std::next(BB->getIterator()), RestoreMBB);
21600   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
21601   BB->addSuccessor(RestoreMBB);
21602   MI->getOperand(0).setMBB(RestoreMBB);
21603
21604   auto RestoreMBBI = RestoreMBB->begin();
21605   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
21606   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
21607   return BB;
21608 }
21609
21610 MachineBasicBlock *
21611 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
21612                                        MachineBasicBlock *BB) const {
21613   MachineFunction *MF = BB->getParent();
21614   const Constant *PerFn = MF->getFunction()->getPersonalityFn();
21615   bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
21616   // Only 32-bit SEH requires special handling for catchpad.
21617   if (IsSEH && Subtarget->is32Bit()) {
21618     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21619     DebugLoc DL = MI->getDebugLoc();
21620     BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
21621   }
21622   MI->eraseFromParent();
21623   return BB;
21624 }
21625
21626 MachineBasicBlock *
21627 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21628                                       MachineBasicBlock *BB) const {
21629   // This is pretty easy.  We're taking the value that we received from
21630   // our load from the relocation, sticking it in either RDI (x86-64)
21631   // or EAX and doing an indirect call.  The return value will then
21632   // be in the normal return register.
21633   MachineFunction *F = BB->getParent();
21634   const X86InstrInfo *TII = Subtarget->getInstrInfo();
21635   DebugLoc DL = MI->getDebugLoc();
21636
21637   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21638   assert(MI->getOperand(3).isGlobal() && "This should be a global");
21639
21640   // Get a register mask for the lowered call.
21641   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21642   // proper register mask.
21643   const uint32_t *RegMask =
21644       Subtarget->is64Bit() ?
21645       Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
21646       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21647   if (Subtarget->is64Bit()) {
21648     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21649                                       TII->get(X86::MOV64rm), X86::RDI)
21650     .addReg(X86::RIP)
21651     .addImm(0).addReg(0)
21652     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21653                       MI->getOperand(3).getTargetFlags())
21654     .addReg(0);
21655     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21656     addDirectMem(MIB, X86::RDI);
21657     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21658   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21659     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21660                                       TII->get(X86::MOV32rm), X86::EAX)
21661     .addReg(0)
21662     .addImm(0).addReg(0)
21663     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21664                       MI->getOperand(3).getTargetFlags())
21665     .addReg(0);
21666     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21667     addDirectMem(MIB, X86::EAX);
21668     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21669   } else {
21670     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21671                                       TII->get(X86::MOV32rm), X86::EAX)
21672     .addReg(TII->getGlobalBaseReg(F))
21673     .addImm(0).addReg(0)
21674     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21675                       MI->getOperand(3).getTargetFlags())
21676     .addReg(0);
21677     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21678     addDirectMem(MIB, X86::EAX);
21679     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21680   }
21681
21682   MI->eraseFromParent(); // The pseudo instruction is gone now.
21683   return BB;
21684 }
21685
21686 MachineBasicBlock *
21687 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21688                                     MachineBasicBlock *MBB) const {
21689   DebugLoc DL = MI->getDebugLoc();
21690   MachineFunction *MF = MBB->getParent();
21691   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21692   MachineRegisterInfo &MRI = MF->getRegInfo();
21693
21694   const BasicBlock *BB = MBB->getBasicBlock();
21695   MachineFunction::iterator I = ++MBB->getIterator();
21696
21697   // Memory Reference
21698   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21699   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21700
21701   unsigned DstReg;
21702   unsigned MemOpndSlot = 0;
21703
21704   unsigned CurOp = 0;
21705
21706   DstReg = MI->getOperand(CurOp++).getReg();
21707   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21708   assert(RC->hasType(MVT::i32) && "Invalid destination!");
21709   unsigned mainDstReg = MRI.createVirtualRegister(RC);
21710   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21711
21712   MemOpndSlot = CurOp;
21713
21714   MVT PVT = getPointerTy(MF->getDataLayout());
21715   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21716          "Invalid Pointer Size!");
21717
21718   // For v = setjmp(buf), we generate
21719   //
21720   // thisMBB:
21721   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21722   //  SjLjSetup restoreMBB
21723   //
21724   // mainMBB:
21725   //  v_main = 0
21726   //
21727   // sinkMBB:
21728   //  v = phi(main, restore)
21729   //
21730   // restoreMBB:
21731   //  if base pointer being used, load it from frame
21732   //  v_restore = 1
21733
21734   MachineBasicBlock *thisMBB = MBB;
21735   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21736   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21737   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21738   MF->insert(I, mainMBB);
21739   MF->insert(I, sinkMBB);
21740   MF->push_back(restoreMBB);
21741   restoreMBB->setHasAddressTaken();
21742
21743   MachineInstrBuilder MIB;
21744
21745   // Transfer the remainder of BB and its successor edges to sinkMBB.
21746   sinkMBB->splice(sinkMBB->begin(), MBB,
21747                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21748   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21749
21750   // thisMBB:
21751   unsigned PtrStoreOpc = 0;
21752   unsigned LabelReg = 0;
21753   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21754   Reloc::Model RM = MF->getTarget().getRelocationModel();
21755   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21756                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21757
21758   // Prepare IP either in reg or imm.
21759   if (!UseImmLabel) {
21760     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21761     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21762     LabelReg = MRI.createVirtualRegister(PtrRC);
21763     if (Subtarget->is64Bit()) {
21764       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21765               .addReg(X86::RIP)
21766               .addImm(0)
21767               .addReg(0)
21768               .addMBB(restoreMBB)
21769               .addReg(0);
21770     } else {
21771       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21772       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21773               .addReg(XII->getGlobalBaseReg(MF))
21774               .addImm(0)
21775               .addReg(0)
21776               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21777               .addReg(0);
21778     }
21779   } else
21780     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21781   // Store IP
21782   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21783   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21784     if (i == X86::AddrDisp)
21785       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21786     else
21787       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21788   }
21789   if (!UseImmLabel)
21790     MIB.addReg(LabelReg);
21791   else
21792     MIB.addMBB(restoreMBB);
21793   MIB.setMemRefs(MMOBegin, MMOEnd);
21794   // Setup
21795   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21796           .addMBB(restoreMBB);
21797
21798   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21799   MIB.addRegMask(RegInfo->getNoPreservedMask());
21800   thisMBB->addSuccessor(mainMBB);
21801   thisMBB->addSuccessor(restoreMBB);
21802
21803   // mainMBB:
21804   //  EAX = 0
21805   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21806   mainMBB->addSuccessor(sinkMBB);
21807
21808   // sinkMBB:
21809   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21810           TII->get(X86::PHI), DstReg)
21811     .addReg(mainDstReg).addMBB(mainMBB)
21812     .addReg(restoreDstReg).addMBB(restoreMBB);
21813
21814   // restoreMBB:
21815   if (RegInfo->hasBasePointer(*MF)) {
21816     const bool Uses64BitFramePtr =
21817         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21818     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21819     X86FI->setRestoreBasePointer(MF);
21820     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21821     unsigned BasePtr = RegInfo->getBaseRegister();
21822     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21823     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21824                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
21825       .setMIFlag(MachineInstr::FrameSetup);
21826   }
21827   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21828   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21829   restoreMBB->addSuccessor(sinkMBB);
21830
21831   MI->eraseFromParent();
21832   return sinkMBB;
21833 }
21834
21835 MachineBasicBlock *
21836 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21837                                      MachineBasicBlock *MBB) const {
21838   DebugLoc DL = MI->getDebugLoc();
21839   MachineFunction *MF = MBB->getParent();
21840   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21841   MachineRegisterInfo &MRI = MF->getRegInfo();
21842
21843   // Memory Reference
21844   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21845   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21846
21847   MVT PVT = getPointerTy(MF->getDataLayout());
21848   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21849          "Invalid Pointer Size!");
21850
21851   const TargetRegisterClass *RC =
21852     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21853   unsigned Tmp = MRI.createVirtualRegister(RC);
21854   // Since FP is only updated here but NOT referenced, it's treated as GPR.
21855   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21856   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21857   unsigned SP = RegInfo->getStackRegister();
21858
21859   MachineInstrBuilder MIB;
21860
21861   const int64_t LabelOffset = 1 * PVT.getStoreSize();
21862   const int64_t SPOffset = 2 * PVT.getStoreSize();
21863
21864   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21865   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21866
21867   // Reload FP
21868   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21869   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21870     MIB.addOperand(MI->getOperand(i));
21871   MIB.setMemRefs(MMOBegin, MMOEnd);
21872   // Reload IP
21873   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21874   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21875     if (i == X86::AddrDisp)
21876       MIB.addDisp(MI->getOperand(i), LabelOffset);
21877     else
21878       MIB.addOperand(MI->getOperand(i));
21879   }
21880   MIB.setMemRefs(MMOBegin, MMOEnd);
21881   // Reload SP
21882   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21883   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21884     if (i == X86::AddrDisp)
21885       MIB.addDisp(MI->getOperand(i), SPOffset);
21886     else
21887       MIB.addOperand(MI->getOperand(i));
21888   }
21889   MIB.setMemRefs(MMOBegin, MMOEnd);
21890   // Jump
21891   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21892
21893   MI->eraseFromParent();
21894   return MBB;
21895 }
21896
21897 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21898 // accumulator loops. Writing back to the accumulator allows the coalescer
21899 // to remove extra copies in the loop.
21900 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
21901 MachineBasicBlock *
21902 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21903                                  MachineBasicBlock *MBB) const {
21904   MachineOperand &AddendOp = MI->getOperand(3);
21905
21906   // Bail out early if the addend isn't a register - we can't switch these.
21907   if (!AddendOp.isReg())
21908     return MBB;
21909
21910   MachineFunction &MF = *MBB->getParent();
21911   MachineRegisterInfo &MRI = MF.getRegInfo();
21912
21913   // Check whether the addend is defined by a PHI:
21914   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21915   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21916   if (!AddendDef.isPHI())
21917     return MBB;
21918
21919   // Look for the following pattern:
21920   // loop:
21921   //   %addend = phi [%entry, 0], [%loop, %result]
21922   //   ...
21923   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21924
21925   // Replace with:
21926   //   loop:
21927   //   %addend = phi [%entry, 0], [%loop, %result]
21928   //   ...
21929   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21930
21931   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21932     assert(AddendDef.getOperand(i).isReg());
21933     MachineOperand PHISrcOp = AddendDef.getOperand(i);
21934     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21935     if (&PHISrcInst == MI) {
21936       // Found a matching instruction.
21937       unsigned NewFMAOpc = 0;
21938       switch (MI->getOpcode()) {
21939         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21940         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21941         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21942         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21943         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21944         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21945         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21946         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21947         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21948         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21949         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21950         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21951         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21952         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21953         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21954         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21955         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21956         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21957         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21958         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21959
21960         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21961         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21962         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21963         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21964         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21965         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21966         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21967         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21968         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21969         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21970         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21971         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21972         default: llvm_unreachable("Unrecognized FMA variant.");
21973       }
21974
21975       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21976       MachineInstrBuilder MIB =
21977         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21978         .addOperand(MI->getOperand(0))
21979         .addOperand(MI->getOperand(3))
21980         .addOperand(MI->getOperand(2))
21981         .addOperand(MI->getOperand(1));
21982       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21983       MI->eraseFromParent();
21984     }
21985   }
21986
21987   return MBB;
21988 }
21989
21990 MachineBasicBlock *
21991 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21992                                                MachineBasicBlock *BB) const {
21993   switch (MI->getOpcode()) {
21994   default: llvm_unreachable("Unexpected instr type to insert");
21995   case X86::TAILJMPd64:
21996   case X86::TAILJMPr64:
21997   case X86::TAILJMPm64:
21998   case X86::TAILJMPd64_REX:
21999   case X86::TAILJMPr64_REX:
22000   case X86::TAILJMPm64_REX:
22001     llvm_unreachable("TAILJMP64 would not be touched here.");
22002   case X86::TCRETURNdi64:
22003   case X86::TCRETURNri64:
22004   case X86::TCRETURNmi64:
22005     return BB;
22006   case X86::WIN_ALLOCA:
22007     return EmitLoweredWinAlloca(MI, BB);
22008   case X86::CATCHRET:
22009     return EmitLoweredCatchRet(MI, BB);
22010   case X86::CATCHPAD:
22011     return EmitLoweredCatchPad(MI, BB);
22012   case X86::SEG_ALLOCA_32:
22013   case X86::SEG_ALLOCA_64:
22014     return EmitLoweredSegAlloca(MI, BB);
22015   case X86::TLSCall_32:
22016   case X86::TLSCall_64:
22017     return EmitLoweredTLSCall(MI, BB);
22018   case X86::CMOV_FR32:
22019   case X86::CMOV_FR64:
22020   case X86::CMOV_GR8:
22021   case X86::CMOV_GR16:
22022   case X86::CMOV_GR32:
22023   case X86::CMOV_RFP32:
22024   case X86::CMOV_RFP64:
22025   case X86::CMOV_RFP80:
22026   case X86::CMOV_V2F64:
22027   case X86::CMOV_V2I64:
22028   case X86::CMOV_V4F32:
22029   case X86::CMOV_V4F64:
22030   case X86::CMOV_V4I64:
22031   case X86::CMOV_V16F32:
22032   case X86::CMOV_V8F32:
22033   case X86::CMOV_V8F64:
22034   case X86::CMOV_V8I64:
22035   case X86::CMOV_V8I1:
22036   case X86::CMOV_V16I1:
22037   case X86::CMOV_V32I1:
22038   case X86::CMOV_V64I1:
22039     return EmitLoweredSelect(MI, BB);
22040
22041   case X86::RELEASE_FADD32mr:
22042   case X86::RELEASE_FADD64mr:
22043     return EmitLoweredAtomicFP(MI, BB);
22044
22045   case X86::FP32_TO_INT16_IN_MEM:
22046   case X86::FP32_TO_INT32_IN_MEM:
22047   case X86::FP32_TO_INT64_IN_MEM:
22048   case X86::FP64_TO_INT16_IN_MEM:
22049   case X86::FP64_TO_INT32_IN_MEM:
22050   case X86::FP64_TO_INT64_IN_MEM:
22051   case X86::FP80_TO_INT16_IN_MEM:
22052   case X86::FP80_TO_INT32_IN_MEM:
22053   case X86::FP80_TO_INT64_IN_MEM: {
22054     MachineFunction *F = BB->getParent();
22055     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22056     DebugLoc DL = MI->getDebugLoc();
22057
22058     // Change the floating point control register to use "round towards zero"
22059     // mode when truncating to an integer value.
22060     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22061     addFrameReference(BuildMI(*BB, MI, DL,
22062                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
22063
22064     // Load the old value of the high byte of the control word...
22065     unsigned OldCW =
22066       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22067     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22068                       CWFrameIdx);
22069
22070     // Set the high part to be round to zero...
22071     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22072       .addImm(0xC7F);
22073
22074     // Reload the modified control word now...
22075     addFrameReference(BuildMI(*BB, MI, DL,
22076                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22077
22078     // Restore the memory image of control word to original value
22079     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22080       .addReg(OldCW);
22081
22082     // Get the X86 opcode to use.
22083     unsigned Opc;
22084     switch (MI->getOpcode()) {
22085     default: llvm_unreachable("illegal opcode!");
22086     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22087     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22088     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22089     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22090     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22091     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22092     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22093     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22094     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22095     }
22096
22097     X86AddressMode AM;
22098     MachineOperand &Op = MI->getOperand(0);
22099     if (Op.isReg()) {
22100       AM.BaseType = X86AddressMode::RegBase;
22101       AM.Base.Reg = Op.getReg();
22102     } else {
22103       AM.BaseType = X86AddressMode::FrameIndexBase;
22104       AM.Base.FrameIndex = Op.getIndex();
22105     }
22106     Op = MI->getOperand(1);
22107     if (Op.isImm())
22108       AM.Scale = Op.getImm();
22109     Op = MI->getOperand(2);
22110     if (Op.isImm())
22111       AM.IndexReg = Op.getImm();
22112     Op = MI->getOperand(3);
22113     if (Op.isGlobal()) {
22114       AM.GV = Op.getGlobal();
22115     } else {
22116       AM.Disp = Op.getImm();
22117     }
22118     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22119                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22120
22121     // Reload the original control word now.
22122     addFrameReference(BuildMI(*BB, MI, DL,
22123                               TII->get(X86::FLDCW16m)), CWFrameIdx);
22124
22125     MI->eraseFromParent();   // The pseudo instruction is gone now.
22126     return BB;
22127   }
22128     // String/text processing lowering.
22129   case X86::PCMPISTRM128REG:
22130   case X86::VPCMPISTRM128REG:
22131   case X86::PCMPISTRM128MEM:
22132   case X86::VPCMPISTRM128MEM:
22133   case X86::PCMPESTRM128REG:
22134   case X86::VPCMPESTRM128REG:
22135   case X86::PCMPESTRM128MEM:
22136   case X86::VPCMPESTRM128MEM:
22137     assert(Subtarget->hasSSE42() &&
22138            "Target must have SSE4.2 or AVX features enabled");
22139     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22140
22141   // String/text processing lowering.
22142   case X86::PCMPISTRIREG:
22143   case X86::VPCMPISTRIREG:
22144   case X86::PCMPISTRIMEM:
22145   case X86::VPCMPISTRIMEM:
22146   case X86::PCMPESTRIREG:
22147   case X86::VPCMPESTRIREG:
22148   case X86::PCMPESTRIMEM:
22149   case X86::VPCMPESTRIMEM:
22150     assert(Subtarget->hasSSE42() &&
22151            "Target must have SSE4.2 or AVX features enabled");
22152     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22153
22154   // Thread synchronization.
22155   case X86::MONITOR:
22156     return EmitMonitor(MI, BB, Subtarget);
22157
22158   // xbegin
22159   case X86::XBEGIN:
22160     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22161
22162   case X86::VASTART_SAVE_XMM_REGS:
22163     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22164
22165   case X86::VAARG_64:
22166     return EmitVAARG64WithCustomInserter(MI, BB);
22167
22168   case X86::EH_SjLj_SetJmp32:
22169   case X86::EH_SjLj_SetJmp64:
22170     return emitEHSjLjSetJmp(MI, BB);
22171
22172   case X86::EH_SjLj_LongJmp32:
22173   case X86::EH_SjLj_LongJmp64:
22174     return emitEHSjLjLongJmp(MI, BB);
22175
22176   case TargetOpcode::STATEPOINT:
22177     // As an implementation detail, STATEPOINT shares the STACKMAP format at
22178     // this point in the process.  We diverge later.
22179     return emitPatchPoint(MI, BB);
22180
22181   case TargetOpcode::STACKMAP:
22182   case TargetOpcode::PATCHPOINT:
22183     return emitPatchPoint(MI, BB);
22184
22185   case X86::VFMADDPDr213r:
22186   case X86::VFMADDPSr213r:
22187   case X86::VFMADDSDr213r:
22188   case X86::VFMADDSSr213r:
22189   case X86::VFMSUBPDr213r:
22190   case X86::VFMSUBPSr213r:
22191   case X86::VFMSUBSDr213r:
22192   case X86::VFMSUBSSr213r:
22193   case X86::VFNMADDPDr213r:
22194   case X86::VFNMADDPSr213r:
22195   case X86::VFNMADDSDr213r:
22196   case X86::VFNMADDSSr213r:
22197   case X86::VFNMSUBPDr213r:
22198   case X86::VFNMSUBPSr213r:
22199   case X86::VFNMSUBSDr213r:
22200   case X86::VFNMSUBSSr213r:
22201   case X86::VFMADDSUBPDr213r:
22202   case X86::VFMADDSUBPSr213r:
22203   case X86::VFMSUBADDPDr213r:
22204   case X86::VFMSUBADDPSr213r:
22205   case X86::VFMADDPDr213rY:
22206   case X86::VFMADDPSr213rY:
22207   case X86::VFMSUBPDr213rY:
22208   case X86::VFMSUBPSr213rY:
22209   case X86::VFNMADDPDr213rY:
22210   case X86::VFNMADDPSr213rY:
22211   case X86::VFNMSUBPDr213rY:
22212   case X86::VFNMSUBPSr213rY:
22213   case X86::VFMADDSUBPDr213rY:
22214   case X86::VFMADDSUBPSr213rY:
22215   case X86::VFMSUBADDPDr213rY:
22216   case X86::VFMSUBADDPSr213rY:
22217     return emitFMA3Instr(MI, BB);
22218   }
22219 }
22220
22221 //===----------------------------------------------------------------------===//
22222 //                           X86 Optimization Hooks
22223 //===----------------------------------------------------------------------===//
22224
22225 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22226                                                       APInt &KnownZero,
22227                                                       APInt &KnownOne,
22228                                                       const SelectionDAG &DAG,
22229                                                       unsigned Depth) const {
22230   unsigned BitWidth = KnownZero.getBitWidth();
22231   unsigned Opc = Op.getOpcode();
22232   assert((Opc >= ISD::BUILTIN_OP_END ||
22233           Opc == ISD::INTRINSIC_WO_CHAIN ||
22234           Opc == ISD::INTRINSIC_W_CHAIN ||
22235           Opc == ISD::INTRINSIC_VOID) &&
22236          "Should use MaskedValueIsZero if you don't know whether Op"
22237          " is a target node!");
22238
22239   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
22240   switch (Opc) {
22241   default: break;
22242   case X86ISD::ADD:
22243   case X86ISD::SUB:
22244   case X86ISD::ADC:
22245   case X86ISD::SBB:
22246   case X86ISD::SMUL:
22247   case X86ISD::UMUL:
22248   case X86ISD::INC:
22249   case X86ISD::DEC:
22250   case X86ISD::OR:
22251   case X86ISD::XOR:
22252   case X86ISD::AND:
22253     // These nodes' second result is a boolean.
22254     if (Op.getResNo() == 0)
22255       break;
22256     // Fallthrough
22257   case X86ISD::SETCC:
22258     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22259     break;
22260   case ISD::INTRINSIC_WO_CHAIN: {
22261     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22262     unsigned NumLoBits = 0;
22263     switch (IntId) {
22264     default: break;
22265     case Intrinsic::x86_sse_movmsk_ps:
22266     case Intrinsic::x86_avx_movmsk_ps_256:
22267     case Intrinsic::x86_sse2_movmsk_pd:
22268     case Intrinsic::x86_avx_movmsk_pd_256:
22269     case Intrinsic::x86_mmx_pmovmskb:
22270     case Intrinsic::x86_sse2_pmovmskb_128:
22271     case Intrinsic::x86_avx2_pmovmskb: {
22272       // High bits of movmskp{s|d}, pmovmskb are known zero.
22273       switch (IntId) {
22274         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
22275         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
22276         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
22277         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
22278         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
22279         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
22280         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
22281         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
22282       }
22283       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22284       break;
22285     }
22286     }
22287     break;
22288   }
22289   }
22290 }
22291
22292 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22293   SDValue Op,
22294   const SelectionDAG &,
22295   unsigned Depth) const {
22296   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22297   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22298     return Op.getValueType().getScalarSizeInBits();
22299
22300   // Fallback case.
22301   return 1;
22302 }
22303
22304 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22305 /// node is a GlobalAddress + offset.
22306 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22307                                        const GlobalValue* &GA,
22308                                        int64_t &Offset) const {
22309   if (N->getOpcode() == X86ISD::Wrapper) {
22310     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22311       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22312       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22313       return true;
22314     }
22315   }
22316   return TargetLowering::isGAPlusOffset(N, GA, Offset);
22317 }
22318
22319 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22320 /// same as extracting the high 128-bit part of 256-bit vector and then
22321 /// inserting the result into the low part of a new 256-bit vector
22322 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22323   EVT VT = SVOp->getValueType(0);
22324   unsigned NumElems = VT.getVectorNumElements();
22325
22326   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22327   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22328     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22329         SVOp->getMaskElt(j) >= 0)
22330       return false;
22331
22332   return true;
22333 }
22334
22335 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22336 /// same as extracting the low 128-bit part of 256-bit vector and then
22337 /// inserting the result into the high part of a new 256-bit vector
22338 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22339   EVT VT = SVOp->getValueType(0);
22340   unsigned NumElems = VT.getVectorNumElements();
22341
22342   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22343   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22344     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22345         SVOp->getMaskElt(j) >= 0)
22346       return false;
22347
22348   return true;
22349 }
22350
22351 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22352 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22353                                         TargetLowering::DAGCombinerInfo &DCI,
22354                                         const X86Subtarget* Subtarget) {
22355   SDLoc dl(N);
22356   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22357   SDValue V1 = SVOp->getOperand(0);
22358   SDValue V2 = SVOp->getOperand(1);
22359   EVT VT = SVOp->getValueType(0);
22360   unsigned NumElems = VT.getVectorNumElements();
22361
22362   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22363       V2.getOpcode() == ISD::CONCAT_VECTORS) {
22364     //
22365     //                   0,0,0,...
22366     //                      |
22367     //    V      UNDEF    BUILD_VECTOR    UNDEF
22368     //     \      /           \           /
22369     //  CONCAT_VECTOR         CONCAT_VECTOR
22370     //         \                  /
22371     //          \                /
22372     //          RESULT: V + zero extended
22373     //
22374     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22375         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22376         V1.getOperand(1).getOpcode() != ISD::UNDEF)
22377       return SDValue();
22378
22379     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22380       return SDValue();
22381
22382     // To match the shuffle mask, the first half of the mask should
22383     // be exactly the first vector, and all the rest a splat with the
22384     // first element of the second one.
22385     for (unsigned i = 0; i != NumElems/2; ++i)
22386       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22387           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22388         return SDValue();
22389
22390     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22391     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22392       if (Ld->hasNUsesOfValue(1, 0)) {
22393         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22394         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22395         SDValue ResNode =
22396           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22397                                   Ld->getMemoryVT(),
22398                                   Ld->getPointerInfo(),
22399                                   Ld->getAlignment(),
22400                                   false/*isVolatile*/, true/*ReadMem*/,
22401                                   false/*WriteMem*/);
22402
22403         // Make sure the newly-created LOAD is in the same position as Ld in
22404         // terms of dependency. We create a TokenFactor for Ld and ResNode,
22405         // and update uses of Ld's output chain to use the TokenFactor.
22406         if (Ld->hasAnyUseOfValue(1)) {
22407           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22408                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22409           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22410           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22411                                  SDValue(ResNode.getNode(), 1));
22412         }
22413
22414         return DAG.getBitcast(VT, ResNode);
22415       }
22416     }
22417
22418     // Emit a zeroed vector and insert the desired subvector on its
22419     // first half.
22420     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22421     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22422     return DCI.CombineTo(N, InsV);
22423   }
22424
22425   //===--------------------------------------------------------------------===//
22426   // Combine some shuffles into subvector extracts and inserts:
22427   //
22428
22429   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22430   if (isShuffleHigh128VectorInsertLow(SVOp)) {
22431     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22432     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22433     return DCI.CombineTo(N, InsV);
22434   }
22435
22436   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22437   if (isShuffleLow128VectorInsertHigh(SVOp)) {
22438     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22439     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22440     return DCI.CombineTo(N, InsV);
22441   }
22442
22443   return SDValue();
22444 }
22445
22446 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22447 /// possible.
22448 ///
22449 /// This is the leaf of the recursive combinine below. When we have found some
22450 /// chain of single-use x86 shuffle instructions and accumulated the combined
22451 /// shuffle mask represented by them, this will try to pattern match that mask
22452 /// into either a single instruction if there is a special purpose instruction
22453 /// for this operation, or into a PSHUFB instruction which is a fully general
22454 /// instruction but should only be used to replace chains over a certain depth.
22455 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22456                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22457                                    TargetLowering::DAGCombinerInfo &DCI,
22458                                    const X86Subtarget *Subtarget) {
22459   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22460
22461   // Find the operand that enters the chain. Note that multiple uses are OK
22462   // here, we're not going to remove the operand we find.
22463   SDValue Input = Op.getOperand(0);
22464   while (Input.getOpcode() == ISD::BITCAST)
22465     Input = Input.getOperand(0);
22466
22467   MVT VT = Input.getSimpleValueType();
22468   MVT RootVT = Root.getSimpleValueType();
22469   SDLoc DL(Root);
22470
22471   if (Mask.size() == 1) {
22472     int Index = Mask[0];
22473     assert((Index >= 0 || Index == SM_SentinelUndef ||
22474             Index == SM_SentinelZero) &&
22475            "Invalid shuffle index found!");
22476
22477     // We may end up with an accumulated mask of size 1 as a result of
22478     // widening of shuffle operands (see function canWidenShuffleElements).
22479     // If the only shuffle index is equal to SM_SentinelZero then propagate
22480     // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22481     // mask, and therefore the entire chain of shuffles can be folded away.
22482     if (Index == SM_SentinelZero)
22483       DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22484     else
22485       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22486                     /*AddTo*/ true);
22487     return true;
22488   }
22489
22490   // Use the float domain if the operand type is a floating point type.
22491   bool FloatDomain = VT.isFloatingPoint();
22492
22493   // For floating point shuffles, we don't have free copies in the shuffle
22494   // instructions or the ability to load as part of the instruction, so
22495   // canonicalize their shuffles to UNPCK or MOV variants.
22496   //
22497   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22498   // vectors because it can have a load folded into it that UNPCK cannot. This
22499   // doesn't preclude something switching to the shorter encoding post-RA.
22500   //
22501   // FIXME: Should teach these routines about AVX vector widths.
22502   if (FloatDomain && VT.is128BitVector()) {
22503     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22504       bool Lo = Mask.equals({0, 0});
22505       unsigned Shuffle;
22506       MVT ShuffleVT;
22507       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22508       // is no slower than UNPCKLPD but has the option to fold the input operand
22509       // into even an unaligned memory load.
22510       if (Lo && Subtarget->hasSSE3()) {
22511         Shuffle = X86ISD::MOVDDUP;
22512         ShuffleVT = MVT::v2f64;
22513       } else {
22514         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22515         // than the UNPCK variants.
22516         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22517         ShuffleVT = MVT::v4f32;
22518       }
22519       if (Depth == 1 && Root->getOpcode() == Shuffle)
22520         return false; // Nothing to do!
22521       Op = DAG.getBitcast(ShuffleVT, Input);
22522       DCI.AddToWorklist(Op.getNode());
22523       if (Shuffle == X86ISD::MOVDDUP)
22524         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22525       else
22526         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22527       DCI.AddToWorklist(Op.getNode());
22528       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22529                     /*AddTo*/ true);
22530       return true;
22531     }
22532     if (Subtarget->hasSSE3() &&
22533         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22534       bool Lo = Mask.equals({0, 0, 2, 2});
22535       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22536       MVT ShuffleVT = MVT::v4f32;
22537       if (Depth == 1 && Root->getOpcode() == Shuffle)
22538         return false; // Nothing to do!
22539       Op = DAG.getBitcast(ShuffleVT, Input);
22540       DCI.AddToWorklist(Op.getNode());
22541       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22542       DCI.AddToWorklist(Op.getNode());
22543       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22544                     /*AddTo*/ true);
22545       return true;
22546     }
22547     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22548       bool Lo = Mask.equals({0, 0, 1, 1});
22549       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22550       MVT ShuffleVT = MVT::v4f32;
22551       if (Depth == 1 && Root->getOpcode() == Shuffle)
22552         return false; // Nothing to do!
22553       Op = DAG.getBitcast(ShuffleVT, Input);
22554       DCI.AddToWorklist(Op.getNode());
22555       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22556       DCI.AddToWorklist(Op.getNode());
22557       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22558                     /*AddTo*/ true);
22559       return true;
22560     }
22561   }
22562
22563   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22564   // variants as none of these have single-instruction variants that are
22565   // superior to the UNPCK formulation.
22566   if (!FloatDomain && VT.is128BitVector() &&
22567       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22568        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22569        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22570        Mask.equals(
22571            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22572     bool Lo = Mask[0] == 0;
22573     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22574     if (Depth == 1 && Root->getOpcode() == Shuffle)
22575       return false; // Nothing to do!
22576     MVT ShuffleVT;
22577     switch (Mask.size()) {
22578     case 8:
22579       ShuffleVT = MVT::v8i16;
22580       break;
22581     case 16:
22582       ShuffleVT = MVT::v16i8;
22583       break;
22584     default:
22585       llvm_unreachable("Impossible mask size!");
22586     };
22587     Op = DAG.getBitcast(ShuffleVT, Input);
22588     DCI.AddToWorklist(Op.getNode());
22589     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22590     DCI.AddToWorklist(Op.getNode());
22591     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22592                   /*AddTo*/ true);
22593     return true;
22594   }
22595
22596   // Don't try to re-form single instruction chains under any circumstances now
22597   // that we've done encoding canonicalization for them.
22598   if (Depth < 2)
22599     return false;
22600
22601   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22602   // can replace them with a single PSHUFB instruction profitably. Intel's
22603   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22604   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22605   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22606     SmallVector<SDValue, 16> PSHUFBMask;
22607     int NumBytes = VT.getSizeInBits() / 8;
22608     int Ratio = NumBytes / Mask.size();
22609     for (int i = 0; i < NumBytes; ++i) {
22610       if (Mask[i / Ratio] == SM_SentinelUndef) {
22611         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22612         continue;
22613       }
22614       int M = Mask[i / Ratio] != SM_SentinelZero
22615                   ? Ratio * Mask[i / Ratio] + i % Ratio
22616                   : 255;
22617       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22618     }
22619     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22620     Op = DAG.getBitcast(ByteVT, Input);
22621     DCI.AddToWorklist(Op.getNode());
22622     SDValue PSHUFBMaskOp =
22623         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22624     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22625     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22626     DCI.AddToWorklist(Op.getNode());
22627     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22628                   /*AddTo*/ true);
22629     return true;
22630   }
22631
22632   // Failed to find any combines.
22633   return false;
22634 }
22635
22636 /// \brief Fully generic combining of x86 shuffle instructions.
22637 ///
22638 /// This should be the last combine run over the x86 shuffle instructions. Once
22639 /// they have been fully optimized, this will recursively consider all chains
22640 /// of single-use shuffle instructions, build a generic model of the cumulative
22641 /// shuffle operation, and check for simpler instructions which implement this
22642 /// operation. We use this primarily for two purposes:
22643 ///
22644 /// 1) Collapse generic shuffles to specialized single instructions when
22645 ///    equivalent. In most cases, this is just an encoding size win, but
22646 ///    sometimes we will collapse multiple generic shuffles into a single
22647 ///    special-purpose shuffle.
22648 /// 2) Look for sequences of shuffle instructions with 3 or more total
22649 ///    instructions, and replace them with the slightly more expensive SSSE3
22650 ///    PSHUFB instruction if available. We do this as the last combining step
22651 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
22652 ///    a suitable short sequence of other instructions. The PHUFB will either
22653 ///    use a register or have to read from memory and so is slightly (but only
22654 ///    slightly) more expensive than the other shuffle instructions.
22655 ///
22656 /// Because this is inherently a quadratic operation (for each shuffle in
22657 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22658 /// This should never be an issue in practice as the shuffle lowering doesn't
22659 /// produce sequences of more than 8 instructions.
22660 ///
22661 /// FIXME: We will currently miss some cases where the redundant shuffling
22662 /// would simplify under the threshold for PSHUFB formation because of
22663 /// combine-ordering. To fix this, we should do the redundant instruction
22664 /// combining in this recursive walk.
22665 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22666                                           ArrayRef<int> RootMask,
22667                                           int Depth, bool HasPSHUFB,
22668                                           SelectionDAG &DAG,
22669                                           TargetLowering::DAGCombinerInfo &DCI,
22670                                           const X86Subtarget *Subtarget) {
22671   // Bound the depth of our recursive combine because this is ultimately
22672   // quadratic in nature.
22673   if (Depth > 8)
22674     return false;
22675
22676   // Directly rip through bitcasts to find the underlying operand.
22677   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22678     Op = Op.getOperand(0);
22679
22680   MVT VT = Op.getSimpleValueType();
22681   if (!VT.isVector())
22682     return false; // Bail if we hit a non-vector.
22683
22684   assert(Root.getSimpleValueType().isVector() &&
22685          "Shuffles operate on vector types!");
22686   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22687          "Can only combine shuffles of the same vector register size.");
22688
22689   if (!isTargetShuffle(Op.getOpcode()))
22690     return false;
22691   SmallVector<int, 16> OpMask;
22692   bool IsUnary;
22693   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22694   // We only can combine unary shuffles which we can decode the mask for.
22695   if (!HaveMask || !IsUnary)
22696     return false;
22697
22698   assert(VT.getVectorNumElements() == OpMask.size() &&
22699          "Different mask size from vector size!");
22700   assert(((RootMask.size() > OpMask.size() &&
22701            RootMask.size() % OpMask.size() == 0) ||
22702           (OpMask.size() > RootMask.size() &&
22703            OpMask.size() % RootMask.size() == 0) ||
22704           OpMask.size() == RootMask.size()) &&
22705          "The smaller number of elements must divide the larger.");
22706   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22707   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22708   assert(((RootRatio == 1 && OpRatio == 1) ||
22709           (RootRatio == 1) != (OpRatio == 1)) &&
22710          "Must not have a ratio for both incoming and op masks!");
22711
22712   SmallVector<int, 16> Mask;
22713   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22714
22715   // Merge this shuffle operation's mask into our accumulated mask. Note that
22716   // this shuffle's mask will be the first applied to the input, followed by the
22717   // root mask to get us all the way to the root value arrangement. The reason
22718   // for this order is that we are recursing up the operation chain.
22719   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22720     int RootIdx = i / RootRatio;
22721     if (RootMask[RootIdx] < 0) {
22722       // This is a zero or undef lane, we're done.
22723       Mask.push_back(RootMask[RootIdx]);
22724       continue;
22725     }
22726
22727     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22728     int OpIdx = RootMaskedIdx / OpRatio;
22729     if (OpMask[OpIdx] < 0) {
22730       // The incoming lanes are zero or undef, it doesn't matter which ones we
22731       // are using.
22732       Mask.push_back(OpMask[OpIdx]);
22733       continue;
22734     }
22735
22736     // Ok, we have non-zero lanes, map them through.
22737     Mask.push_back(OpMask[OpIdx] * OpRatio +
22738                    RootMaskedIdx % OpRatio);
22739   }
22740
22741   // See if we can recurse into the operand to combine more things.
22742   switch (Op.getOpcode()) {
22743   case X86ISD::PSHUFB:
22744     HasPSHUFB = true;
22745   case X86ISD::PSHUFD:
22746   case X86ISD::PSHUFHW:
22747   case X86ISD::PSHUFLW:
22748     if (Op.getOperand(0).hasOneUse() &&
22749         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22750                                       HasPSHUFB, DAG, DCI, Subtarget))
22751       return true;
22752     break;
22753
22754   case X86ISD::UNPCKL:
22755   case X86ISD::UNPCKH:
22756     assert(Op.getOperand(0) == Op.getOperand(1) &&
22757            "We only combine unary shuffles!");
22758     // We can't check for single use, we have to check that this shuffle is the
22759     // only user.
22760     if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22761         combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22762                                       HasPSHUFB, DAG, DCI, Subtarget))
22763       return true;
22764     break;
22765   }
22766
22767   // Minor canonicalization of the accumulated shuffle mask to make it easier
22768   // to match below. All this does is detect masks with squential pairs of
22769   // elements, and shrink them to the half-width mask. It does this in a loop
22770   // so it will reduce the size of the mask to the minimal width mask which
22771   // performs an equivalent shuffle.
22772   SmallVector<int, 16> WidenedMask;
22773   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22774     Mask = std::move(WidenedMask);
22775     WidenedMask.clear();
22776   }
22777
22778   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22779                                 Subtarget);
22780 }
22781
22782 /// \brief Get the PSHUF-style mask from PSHUF node.
22783 ///
22784 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22785 /// PSHUF-style masks that can be reused with such instructions.
22786 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22787   MVT VT = N.getSimpleValueType();
22788   SmallVector<int, 4> Mask;
22789   bool IsUnary;
22790   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22791   (void)HaveMask;
22792   assert(HaveMask);
22793
22794   // If we have more than 128-bits, only the low 128-bits of shuffle mask
22795   // matter. Check that the upper masks are repeats and remove them.
22796   if (VT.getSizeInBits() > 128) {
22797     int LaneElts = 128 / VT.getScalarSizeInBits();
22798 #ifndef NDEBUG
22799     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22800       for (int j = 0; j < LaneElts; ++j)
22801         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22802                "Mask doesn't repeat in high 128-bit lanes!");
22803 #endif
22804     Mask.resize(LaneElts);
22805   }
22806
22807   switch (N.getOpcode()) {
22808   case X86ISD::PSHUFD:
22809     return Mask;
22810   case X86ISD::PSHUFLW:
22811     Mask.resize(4);
22812     return Mask;
22813   case X86ISD::PSHUFHW:
22814     Mask.erase(Mask.begin(), Mask.begin() + 4);
22815     for (int &M : Mask)
22816       M -= 4;
22817     return Mask;
22818   default:
22819     llvm_unreachable("No valid shuffle instruction found!");
22820   }
22821 }
22822
22823 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22824 ///
22825 /// We walk up the chain and look for a combinable shuffle, skipping over
22826 /// shuffles that we could hoist this shuffle's transformation past without
22827 /// altering anything.
22828 static SDValue
22829 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22830                              SelectionDAG &DAG,
22831                              TargetLowering::DAGCombinerInfo &DCI) {
22832   assert(N.getOpcode() == X86ISD::PSHUFD &&
22833          "Called with something other than an x86 128-bit half shuffle!");
22834   SDLoc DL(N);
22835
22836   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22837   // of the shuffles in the chain so that we can form a fresh chain to replace
22838   // this one.
22839   SmallVector<SDValue, 8> Chain;
22840   SDValue V = N.getOperand(0);
22841   for (; V.hasOneUse(); V = V.getOperand(0)) {
22842     switch (V.getOpcode()) {
22843     default:
22844       return SDValue(); // Nothing combined!
22845
22846     case ISD::BITCAST:
22847       // Skip bitcasts as we always know the type for the target specific
22848       // instructions.
22849       continue;
22850
22851     case X86ISD::PSHUFD:
22852       // Found another dword shuffle.
22853       break;
22854
22855     case X86ISD::PSHUFLW:
22856       // Check that the low words (being shuffled) are the identity in the
22857       // dword shuffle, and the high words are self-contained.
22858       if (Mask[0] != 0 || Mask[1] != 1 ||
22859           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22860         return SDValue();
22861
22862       Chain.push_back(V);
22863       continue;
22864
22865     case X86ISD::PSHUFHW:
22866       // Check that the high words (being shuffled) are the identity in the
22867       // dword shuffle, and the low words are self-contained.
22868       if (Mask[2] != 2 || Mask[3] != 3 ||
22869           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22870         return SDValue();
22871
22872       Chain.push_back(V);
22873       continue;
22874
22875     case X86ISD::UNPCKL:
22876     case X86ISD::UNPCKH:
22877       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22878       // shuffle into a preceding word shuffle.
22879       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
22880           V.getSimpleValueType().getVectorElementType() != MVT::i16)
22881         return SDValue();
22882
22883       // Search for a half-shuffle which we can combine with.
22884       unsigned CombineOp =
22885           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22886       if (V.getOperand(0) != V.getOperand(1) ||
22887           !V->isOnlyUserOf(V.getOperand(0).getNode()))
22888         return SDValue();
22889       Chain.push_back(V);
22890       V = V.getOperand(0);
22891       do {
22892         switch (V.getOpcode()) {
22893         default:
22894           return SDValue(); // Nothing to combine.
22895
22896         case X86ISD::PSHUFLW:
22897         case X86ISD::PSHUFHW:
22898           if (V.getOpcode() == CombineOp)
22899             break;
22900
22901           Chain.push_back(V);
22902
22903           // Fallthrough!
22904         case ISD::BITCAST:
22905           V = V.getOperand(0);
22906           continue;
22907         }
22908         break;
22909       } while (V.hasOneUse());
22910       break;
22911     }
22912     // Break out of the loop if we break out of the switch.
22913     break;
22914   }
22915
22916   if (!V.hasOneUse())
22917     // We fell out of the loop without finding a viable combining instruction.
22918     return SDValue();
22919
22920   // Merge this node's mask and our incoming mask.
22921   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22922   for (int &M : Mask)
22923     M = VMask[M];
22924   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22925                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22926
22927   // Rebuild the chain around this new shuffle.
22928   while (!Chain.empty()) {
22929     SDValue W = Chain.pop_back_val();
22930
22931     if (V.getValueType() != W.getOperand(0).getValueType())
22932       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22933
22934     switch (W.getOpcode()) {
22935     default:
22936       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22937
22938     case X86ISD::UNPCKL:
22939     case X86ISD::UNPCKH:
22940       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22941       break;
22942
22943     case X86ISD::PSHUFD:
22944     case X86ISD::PSHUFLW:
22945     case X86ISD::PSHUFHW:
22946       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22947       break;
22948     }
22949   }
22950   if (V.getValueType() != N.getValueType())
22951     V = DAG.getBitcast(N.getValueType(), V);
22952
22953   // Return the new chain to replace N.
22954   return V;
22955 }
22956
22957 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22958 /// pshufhw.
22959 ///
22960 /// We walk up the chain, skipping shuffles of the other half and looking
22961 /// through shuffles which switch halves trying to find a shuffle of the same
22962 /// pair of dwords.
22963 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22964                                         SelectionDAG &DAG,
22965                                         TargetLowering::DAGCombinerInfo &DCI) {
22966   assert(
22967       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22968       "Called with something other than an x86 128-bit half shuffle!");
22969   SDLoc DL(N);
22970   unsigned CombineOpcode = N.getOpcode();
22971
22972   // Walk up a single-use chain looking for a combinable shuffle.
22973   SDValue V = N.getOperand(0);
22974   for (; V.hasOneUse(); V = V.getOperand(0)) {
22975     switch (V.getOpcode()) {
22976     default:
22977       return false; // Nothing combined!
22978
22979     case ISD::BITCAST:
22980       // Skip bitcasts as we always know the type for the target specific
22981       // instructions.
22982       continue;
22983
22984     case X86ISD::PSHUFLW:
22985     case X86ISD::PSHUFHW:
22986       if (V.getOpcode() == CombineOpcode)
22987         break;
22988
22989       // Other-half shuffles are no-ops.
22990       continue;
22991     }
22992     // Break out of the loop if we break out of the switch.
22993     break;
22994   }
22995
22996   if (!V.hasOneUse())
22997     // We fell out of the loop without finding a viable combining instruction.
22998     return false;
22999
23000   // Combine away the bottom node as its shuffle will be accumulated into
23001   // a preceding shuffle.
23002   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23003
23004   // Record the old value.
23005   SDValue Old = V;
23006
23007   // Merge this node's mask and our incoming mask (adjusted to account for all
23008   // the pshufd instructions encountered).
23009   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23010   for (int &M : Mask)
23011     M = VMask[M];
23012   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23013                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23014
23015   // Check that the shuffles didn't cancel each other out. If not, we need to
23016   // combine to the new one.
23017   if (Old != V)
23018     // Replace the combinable shuffle with the combined one, updating all users
23019     // so that we re-evaluate the chain here.
23020     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23021
23022   return true;
23023 }
23024
23025 /// \brief Try to combine x86 target specific shuffles.
23026 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23027                                            TargetLowering::DAGCombinerInfo &DCI,
23028                                            const X86Subtarget *Subtarget) {
23029   SDLoc DL(N);
23030   MVT VT = N.getSimpleValueType();
23031   SmallVector<int, 4> Mask;
23032
23033   switch (N.getOpcode()) {
23034   case X86ISD::PSHUFD:
23035   case X86ISD::PSHUFLW:
23036   case X86ISD::PSHUFHW:
23037     Mask = getPSHUFShuffleMask(N);
23038     assert(Mask.size() == 4);
23039     break;
23040   case X86ISD::UNPCKL: {
23041     // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23042     // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23043     // moves upper half elements into the lower half part. For example:
23044     //
23045     // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23046     //     undef:v16i8
23047     // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23048     //
23049     // will be combined to:
23050     //
23051     // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23052
23053     // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23054     // happen due to advanced instructions.
23055     if (!VT.is128BitVector())
23056       return SDValue();
23057
23058     auto Op0 = N.getOperand(0);
23059     auto Op1 = N.getOperand(1);
23060     if (Op0.getOpcode() == ISD::UNDEF &&
23061         Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23062       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23063
23064       unsigned NumElts = VT.getVectorNumElements();
23065       SmallVector<int, 8> ExpectedMask(NumElts, -1);
23066       std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23067                 NumElts / 2);
23068
23069       auto ShufOp = Op1.getOperand(0);
23070       if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23071         return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23072     }
23073     return SDValue();
23074   }
23075   default:
23076     return SDValue();
23077   }
23078
23079   // Nuke no-op shuffles that show up after combining.
23080   if (isNoopShuffleMask(Mask))
23081     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23082
23083   // Look for simplifications involving one or two shuffle instructions.
23084   SDValue V = N.getOperand(0);
23085   switch (N.getOpcode()) {
23086   default:
23087     break;
23088   case X86ISD::PSHUFLW:
23089   case X86ISD::PSHUFHW:
23090     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23091
23092     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23093       return SDValue(); // We combined away this shuffle, so we're done.
23094
23095     // See if this reduces to a PSHUFD which is no more expensive and can
23096     // combine with more operations. Note that it has to at least flip the
23097     // dwords as otherwise it would have been removed as a no-op.
23098     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23099       int DMask[] = {0, 1, 2, 3};
23100       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23101       DMask[DOffset + 0] = DOffset + 1;
23102       DMask[DOffset + 1] = DOffset + 0;
23103       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23104       V = DAG.getBitcast(DVT, V);
23105       DCI.AddToWorklist(V.getNode());
23106       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23107                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23108       DCI.AddToWorklist(V.getNode());
23109       return DAG.getBitcast(VT, V);
23110     }
23111
23112     // Look for shuffle patterns which can be implemented as a single unpack.
23113     // FIXME: This doesn't handle the location of the PSHUFD generically, and
23114     // only works when we have a PSHUFD followed by two half-shuffles.
23115     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23116         (V.getOpcode() == X86ISD::PSHUFLW ||
23117          V.getOpcode() == X86ISD::PSHUFHW) &&
23118         V.getOpcode() != N.getOpcode() &&
23119         V.hasOneUse()) {
23120       SDValue D = V.getOperand(0);
23121       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23122         D = D.getOperand(0);
23123       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23124         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23125         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23126         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23127         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23128         int WordMask[8];
23129         for (int i = 0; i < 4; ++i) {
23130           WordMask[i + NOffset] = Mask[i] + NOffset;
23131           WordMask[i + VOffset] = VMask[i] + VOffset;
23132         }
23133         // Map the word mask through the DWord mask.
23134         int MappedMask[8];
23135         for (int i = 0; i < 8; ++i)
23136           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23137         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23138             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23139           // We can replace all three shuffles with an unpack.
23140           V = DAG.getBitcast(VT, D.getOperand(0));
23141           DCI.AddToWorklist(V.getNode());
23142           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23143                                                 : X86ISD::UNPCKH,
23144                              DL, VT, V, V);
23145         }
23146       }
23147     }
23148
23149     break;
23150
23151   case X86ISD::PSHUFD:
23152     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23153       return NewN;
23154
23155     break;
23156   }
23157
23158   return SDValue();
23159 }
23160
23161 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23162 ///
23163 /// We combine this directly on the abstract vector shuffle nodes so it is
23164 /// easier to generically match. We also insert dummy vector shuffle nodes for
23165 /// the operands which explicitly discard the lanes which are unused by this
23166 /// operation to try to flow through the rest of the combiner the fact that
23167 /// they're unused.
23168 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23169   SDLoc DL(N);
23170   EVT VT = N->getValueType(0);
23171
23172   // We only handle target-independent shuffles.
23173   // FIXME: It would be easy and harmless to use the target shuffle mask
23174   // extraction tool to support more.
23175   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23176     return SDValue();
23177
23178   auto *SVN = cast<ShuffleVectorSDNode>(N);
23179   ArrayRef<int> Mask = SVN->getMask();
23180   SDValue V1 = N->getOperand(0);
23181   SDValue V2 = N->getOperand(1);
23182
23183   // We require the first shuffle operand to be the SUB node, and the second to
23184   // be the ADD node.
23185   // FIXME: We should support the commuted patterns.
23186   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
23187     return SDValue();
23188
23189   // If there are other uses of these operations we can't fold them.
23190   if (!V1->hasOneUse() || !V2->hasOneUse())
23191     return SDValue();
23192
23193   // Ensure that both operations have the same operands. Note that we can
23194   // commute the FADD operands.
23195   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23196   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23197       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23198     return SDValue();
23199
23200   // We're looking for blends between FADD and FSUB nodes. We insist on these
23201   // nodes being lined up in a specific expected pattern.
23202   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23203         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23204         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23205     return SDValue();
23206
23207   // Only specific types are legal at this point, assert so we notice if and
23208   // when these change.
23209   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23210           VT == MVT::v4f64) &&
23211          "Unknown vector type encountered!");
23212
23213   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23214 }
23215
23216 /// PerformShuffleCombine - Performs several different shuffle combines.
23217 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23218                                      TargetLowering::DAGCombinerInfo &DCI,
23219                                      const X86Subtarget *Subtarget) {
23220   SDLoc dl(N);
23221   SDValue N0 = N->getOperand(0);
23222   SDValue N1 = N->getOperand(1);
23223   EVT VT = N->getValueType(0);
23224
23225   // Don't create instructions with illegal types after legalize types has run.
23226   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23227   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23228     return SDValue();
23229
23230   // If we have legalized the vector types, look for blends of FADD and FSUB
23231   // nodes that we can fuse into an ADDSUB node.
23232   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23233     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23234       return AddSub;
23235
23236   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23237   if (Subtarget->hasFp256() && VT.is256BitVector() &&
23238       N->getOpcode() == ISD::VECTOR_SHUFFLE)
23239     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23240
23241   // During Type Legalization, when promoting illegal vector types,
23242   // the backend might introduce new shuffle dag nodes and bitcasts.
23243   //
23244   // This code performs the following transformation:
23245   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23246   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23247   //
23248   // We do this only if both the bitcast and the BINOP dag nodes have
23249   // one use. Also, perform this transformation only if the new binary
23250   // operation is legal. This is to avoid introducing dag nodes that
23251   // potentially need to be further expanded (or custom lowered) into a
23252   // less optimal sequence of dag nodes.
23253   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23254       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23255       N0.getOpcode() == ISD::BITCAST) {
23256     SDValue BC0 = N0.getOperand(0);
23257     EVT SVT = BC0.getValueType();
23258     unsigned Opcode = BC0.getOpcode();
23259     unsigned NumElts = VT.getVectorNumElements();
23260
23261     if (BC0.hasOneUse() && SVT.isVector() &&
23262         SVT.getVectorNumElements() * 2 == NumElts &&
23263         TLI.isOperationLegal(Opcode, VT)) {
23264       bool CanFold = false;
23265       switch (Opcode) {
23266       default : break;
23267       case ISD::ADD :
23268       case ISD::FADD :
23269       case ISD::SUB :
23270       case ISD::FSUB :
23271       case ISD::MUL :
23272       case ISD::FMUL :
23273         CanFold = true;
23274       }
23275
23276       unsigned SVTNumElts = SVT.getVectorNumElements();
23277       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23278       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23279         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23280       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23281         CanFold = SVOp->getMaskElt(i) < 0;
23282
23283       if (CanFold) {
23284         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23285         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23286         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23287         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23288       }
23289     }
23290   }
23291
23292   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23293   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23294   // consecutive, non-overlapping, and in the right order.
23295   SmallVector<SDValue, 16> Elts;
23296   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23297     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23298
23299   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23300     return LD;
23301
23302   if (isTargetShuffle(N->getOpcode())) {
23303     SDValue Shuffle =
23304         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23305     if (Shuffle.getNode())
23306       return Shuffle;
23307
23308     // Try recursively combining arbitrary sequences of x86 shuffle
23309     // instructions into higher-order shuffles. We do this after combining
23310     // specific PSHUF instruction sequences into their minimal form so that we
23311     // can evaluate how many specialized shuffle instructions are involved in
23312     // a particular chain.
23313     SmallVector<int, 1> NonceMask; // Just a placeholder.
23314     NonceMask.push_back(0);
23315     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23316                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23317                                       DCI, Subtarget))
23318       return SDValue(); // This routine will use CombineTo to replace N.
23319   }
23320
23321   return SDValue();
23322 }
23323
23324 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23325 /// specific shuffle of a load can be folded into a single element load.
23326 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23327 /// shuffles have been custom lowered so we need to handle those here.
23328 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23329                                          TargetLowering::DAGCombinerInfo &DCI) {
23330   if (DCI.isBeforeLegalizeOps())
23331     return SDValue();
23332
23333   SDValue InVec = N->getOperand(0);
23334   SDValue EltNo = N->getOperand(1);
23335
23336   if (!isa<ConstantSDNode>(EltNo))
23337     return SDValue();
23338
23339   EVT OriginalVT = InVec.getValueType();
23340
23341   if (InVec.getOpcode() == ISD::BITCAST) {
23342     // Don't duplicate a load with other uses.
23343     if (!InVec.hasOneUse())
23344       return SDValue();
23345     EVT BCVT = InVec.getOperand(0).getValueType();
23346     if (!BCVT.isVector() ||
23347         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23348       return SDValue();
23349     InVec = InVec.getOperand(0);
23350   }
23351
23352   EVT CurrentVT = InVec.getValueType();
23353
23354   if (!isTargetShuffle(InVec.getOpcode()))
23355     return SDValue();
23356
23357   // Don't duplicate a load with other uses.
23358   if (!InVec.hasOneUse())
23359     return SDValue();
23360
23361   SmallVector<int, 16> ShuffleMask;
23362   bool UnaryShuffle;
23363   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23364                             ShuffleMask, UnaryShuffle))
23365     return SDValue();
23366
23367   // Select the input vector, guarding against out of range extract vector.
23368   unsigned NumElems = CurrentVT.getVectorNumElements();
23369   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23370   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23371   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23372                                          : InVec.getOperand(1);
23373
23374   // If inputs to shuffle are the same for both ops, then allow 2 uses
23375   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23376                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23377
23378   if (LdNode.getOpcode() == ISD::BITCAST) {
23379     // Don't duplicate a load with other uses.
23380     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23381       return SDValue();
23382
23383     AllowedUses = 1; // only allow 1 load use if we have a bitcast
23384     LdNode = LdNode.getOperand(0);
23385   }
23386
23387   if (!ISD::isNormalLoad(LdNode.getNode()))
23388     return SDValue();
23389
23390   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23391
23392   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23393     return SDValue();
23394
23395   EVT EltVT = N->getValueType(0);
23396   // If there's a bitcast before the shuffle, check if the load type and
23397   // alignment is valid.
23398   unsigned Align = LN0->getAlignment();
23399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23400   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23401       EltVT.getTypeForEVT(*DAG.getContext()));
23402
23403   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23404     return SDValue();
23405
23406   // All checks match so transform back to vector_shuffle so that DAG combiner
23407   // can finish the job
23408   SDLoc dl(N);
23409
23410   // Create shuffle node taking into account the case that its a unary shuffle
23411   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23412                                    : InVec.getOperand(1);
23413   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23414                                  InVec.getOperand(0), Shuffle,
23415                                  &ShuffleMask[0]);
23416   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23417   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23418                      EltNo);
23419 }
23420
23421 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23422                                      const X86Subtarget *Subtarget) {
23423   SDValue N0 = N->getOperand(0);
23424   EVT VT = N->getValueType(0);
23425
23426   // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23427   // special and don't usually play with other vector types, it's better to
23428   // handle them early to be sure we emit efficient code by avoiding
23429   // store-load conversions.
23430   if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23431       N0.getValueType() == MVT::v2i32 &&
23432       isa<ConstantSDNode>(N0.getOperand(1))) {
23433     SDValue N00 = N0->getOperand(0);
23434     if (N0.getConstantOperandVal(1) == 0 && N00.getValueType() == MVT::i32)
23435       return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23436   }
23437
23438   // Convert a bitcasted integer logic operation that has one bitcasted
23439   // floating-point operand and one constant operand into a floating-point
23440   // logic operation. This may create a load of the constant, but that is
23441   // cheaper than materializing the constant in an integer register and
23442   // transferring it to an SSE register or transferring the SSE operand to
23443   // integer register and back.
23444   unsigned FPOpcode;
23445   switch (N0.getOpcode()) {
23446     case ISD::AND: FPOpcode = X86ISD::FAND; break;
23447     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
23448     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23449     default: return SDValue();
23450   }
23451   if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23452        (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23453       isa<ConstantSDNode>(N0.getOperand(1)) &&
23454       N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23455       N0.getOperand(0).getOperand(0).getValueType() == VT) {
23456     SDValue N000 = N0.getOperand(0).getOperand(0);
23457     SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23458     return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23459   }
23460
23461   return SDValue();
23462 }
23463
23464 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23465 /// generation and convert it from being a bunch of shuffles and extracts
23466 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23467 /// storing the value and loading scalars back, while for x64 we should
23468 /// use 64-bit extracts and shifts.
23469 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23470                                          TargetLowering::DAGCombinerInfo &DCI) {
23471   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23472     return NewOp;
23473
23474   SDValue InputVector = N->getOperand(0);
23475   SDLoc dl(InputVector);
23476   // Detect mmx to i32 conversion through a v2i32 elt extract.
23477   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23478       N->getValueType(0) == MVT::i32 &&
23479       InputVector.getValueType() == MVT::v2i32) {
23480
23481     // The bitcast source is a direct mmx result.
23482     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23483     if (MMXSrc.getValueType() == MVT::x86mmx)
23484       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23485                          N->getValueType(0),
23486                          InputVector.getNode()->getOperand(0));
23487
23488     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23489     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23490         MMXSrc.getValueType() == MVT::i64) {
23491       SDValue MMXSrcOp = MMXSrc.getOperand(0);
23492       if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23493           MMXSrcOp.getValueType() == MVT::v1i64 &&
23494           MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23495         return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23496                            N->getValueType(0), MMXSrcOp.getOperand(0));
23497     }
23498   }
23499
23500   EVT VT = N->getValueType(0);
23501
23502   if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23503       InputVector.getOpcode() == ISD::BITCAST &&
23504       isa<ConstantSDNode>(InputVector.getOperand(0))) {
23505     uint64_t ExtractedElt =
23506         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23507     uint64_t InputValue =
23508         cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23509     uint64_t Res = (InputValue >> ExtractedElt) & 1;
23510     return DAG.getConstant(Res, dl, MVT::i1);
23511   }
23512   // Only operate on vectors of 4 elements, where the alternative shuffling
23513   // gets to be more expensive.
23514   if (InputVector.getValueType() != MVT::v4i32)
23515     return SDValue();
23516
23517   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23518   // single use which is a sign-extend or zero-extend, and all elements are
23519   // used.
23520   SmallVector<SDNode *, 4> Uses;
23521   unsigned ExtractedElements = 0;
23522   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23523        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23524     if (UI.getUse().getResNo() != InputVector.getResNo())
23525       return SDValue();
23526
23527     SDNode *Extract = *UI;
23528     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23529       return SDValue();
23530
23531     if (Extract->getValueType(0) != MVT::i32)
23532       return SDValue();
23533     if (!Extract->hasOneUse())
23534       return SDValue();
23535     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23536         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23537       return SDValue();
23538     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23539       return SDValue();
23540
23541     // Record which element was extracted.
23542     ExtractedElements |=
23543       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23544
23545     Uses.push_back(Extract);
23546   }
23547
23548   // If not all the elements were used, this may not be worthwhile.
23549   if (ExtractedElements != 15)
23550     return SDValue();
23551
23552   // Ok, we've now decided to do the transformation.
23553   // If 64-bit shifts are legal, use the extract-shift sequence,
23554   // otherwise bounce the vector off the cache.
23555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23556   SDValue Vals[4];
23557
23558   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23559     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23560     auto &DL = DAG.getDataLayout();
23561     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23562     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23563       DAG.getConstant(0, dl, VecIdxTy));
23564     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23565       DAG.getConstant(1, dl, VecIdxTy));
23566
23567     SDValue ShAmt = DAG.getConstant(
23568         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23569     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23570     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23571       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23572     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23573     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23574       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23575   } else {
23576     // Store the value to a temporary stack slot.
23577     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23578     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23579       MachinePointerInfo(), false, false, 0);
23580
23581     EVT ElementType = InputVector.getValueType().getVectorElementType();
23582     unsigned EltSize = ElementType.getSizeInBits() / 8;
23583
23584     // Replace each use (extract) with a load of the appropriate element.
23585     for (unsigned i = 0; i < 4; ++i) {
23586       uint64_t Offset = EltSize * i;
23587       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23588       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23589
23590       SDValue ScalarAddr =
23591           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23592
23593       // Load the scalar.
23594       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23595                             ScalarAddr, MachinePointerInfo(),
23596                             false, false, false, 0);
23597
23598     }
23599   }
23600
23601   // Replace the extracts
23602   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23603     UE = Uses.end(); UI != UE; ++UI) {
23604     SDNode *Extract = *UI;
23605
23606     SDValue Idx = Extract->getOperand(1);
23607     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23608     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23609   }
23610
23611   // The replacement was made in place; don't return anything.
23612   return SDValue();
23613 }
23614
23615 static SDValue
23616 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23617                                       const X86Subtarget *Subtarget) {
23618   SDLoc dl(N);
23619   SDValue Cond = N->getOperand(0);
23620   SDValue LHS = N->getOperand(1);
23621   SDValue RHS = N->getOperand(2);
23622
23623   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23624     SDValue CondSrc = Cond->getOperand(0);
23625     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23626       Cond = CondSrc->getOperand(0);
23627   }
23628
23629   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23630     return SDValue();
23631
23632   // A vselect where all conditions and data are constants can be optimized into
23633   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23634   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23635       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23636     return SDValue();
23637
23638   unsigned MaskValue = 0;
23639   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23640     return SDValue();
23641
23642   MVT VT = N->getSimpleValueType(0);
23643   unsigned NumElems = VT.getVectorNumElements();
23644   SmallVector<int, 8> ShuffleMask(NumElems, -1);
23645   for (unsigned i = 0; i < NumElems; ++i) {
23646     // Be sure we emit undef where we can.
23647     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23648       ShuffleMask[i] = -1;
23649     else
23650       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23651   }
23652
23653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23654   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23655     return SDValue();
23656   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23657 }
23658
23659 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23660 /// nodes.
23661 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23662                                     TargetLowering::DAGCombinerInfo &DCI,
23663                                     const X86Subtarget *Subtarget) {
23664   SDLoc DL(N);
23665   SDValue Cond = N->getOperand(0);
23666   // Get the LHS/RHS of the select.
23667   SDValue LHS = N->getOperand(1);
23668   SDValue RHS = N->getOperand(2);
23669   EVT VT = LHS.getValueType();
23670   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23671
23672   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23673   // instructions match the semantics of the common C idiom x<y?x:y but not
23674   // x<=y?x:y, because of how they handle negative zero (which can be
23675   // ignored in unsafe-math mode).
23676   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23677   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23678       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23679       (Subtarget->hasSSE2() ||
23680        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23681     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23682
23683     unsigned Opcode = 0;
23684     // Check for x CC y ? x : y.
23685     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23686         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23687       switch (CC) {
23688       default: break;
23689       case ISD::SETULT:
23690         // Converting this to a min would handle NaNs incorrectly, and swapping
23691         // the operands would cause it to handle comparisons between positive
23692         // and negative zero incorrectly.
23693         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23694           if (!DAG.getTarget().Options.UnsafeFPMath &&
23695               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23696             break;
23697           std::swap(LHS, RHS);
23698         }
23699         Opcode = X86ISD::FMIN;
23700         break;
23701       case ISD::SETOLE:
23702         // Converting this to a min would handle comparisons between positive
23703         // and negative zero incorrectly.
23704         if (!DAG.getTarget().Options.UnsafeFPMath &&
23705             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23706           break;
23707         Opcode = X86ISD::FMIN;
23708         break;
23709       case ISD::SETULE:
23710         // Converting this to a min would handle both negative zeros and NaNs
23711         // incorrectly, but we can swap the operands to fix both.
23712         std::swap(LHS, RHS);
23713       case ISD::SETOLT:
23714       case ISD::SETLT:
23715       case ISD::SETLE:
23716         Opcode = X86ISD::FMIN;
23717         break;
23718
23719       case ISD::SETOGE:
23720         // Converting this to a max would handle comparisons between positive
23721         // and negative zero incorrectly.
23722         if (!DAG.getTarget().Options.UnsafeFPMath &&
23723             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23724           break;
23725         Opcode = X86ISD::FMAX;
23726         break;
23727       case ISD::SETUGT:
23728         // Converting this to a max would handle NaNs incorrectly, and swapping
23729         // the operands would cause it to handle comparisons between positive
23730         // and negative zero incorrectly.
23731         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23732           if (!DAG.getTarget().Options.UnsafeFPMath &&
23733               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23734             break;
23735           std::swap(LHS, RHS);
23736         }
23737         Opcode = X86ISD::FMAX;
23738         break;
23739       case ISD::SETUGE:
23740         // Converting this to a max would handle both negative zeros and NaNs
23741         // incorrectly, but we can swap the operands to fix both.
23742         std::swap(LHS, RHS);
23743       case ISD::SETOGT:
23744       case ISD::SETGT:
23745       case ISD::SETGE:
23746         Opcode = X86ISD::FMAX;
23747         break;
23748       }
23749     // Check for x CC y ? y : x -- a min/max with reversed arms.
23750     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23751                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23752       switch (CC) {
23753       default: break;
23754       case ISD::SETOGE:
23755         // Converting this to a min would handle comparisons between positive
23756         // and negative zero incorrectly, and swapping the operands would
23757         // cause it to handle NaNs incorrectly.
23758         if (!DAG.getTarget().Options.UnsafeFPMath &&
23759             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23760           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23761             break;
23762           std::swap(LHS, RHS);
23763         }
23764         Opcode = X86ISD::FMIN;
23765         break;
23766       case ISD::SETUGT:
23767         // Converting this to a min would handle NaNs incorrectly.
23768         if (!DAG.getTarget().Options.UnsafeFPMath &&
23769             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23770           break;
23771         Opcode = X86ISD::FMIN;
23772         break;
23773       case ISD::SETUGE:
23774         // Converting this to a min would handle both negative zeros and NaNs
23775         // incorrectly, but we can swap the operands to fix both.
23776         std::swap(LHS, RHS);
23777       case ISD::SETOGT:
23778       case ISD::SETGT:
23779       case ISD::SETGE:
23780         Opcode = X86ISD::FMIN;
23781         break;
23782
23783       case ISD::SETULT:
23784         // Converting this to a max would handle NaNs incorrectly.
23785         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23786           break;
23787         Opcode = X86ISD::FMAX;
23788         break;
23789       case ISD::SETOLE:
23790         // Converting this to a max would handle comparisons between positive
23791         // and negative zero incorrectly, and swapping the operands would
23792         // cause it to handle NaNs incorrectly.
23793         if (!DAG.getTarget().Options.UnsafeFPMath &&
23794             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23795           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23796             break;
23797           std::swap(LHS, RHS);
23798         }
23799         Opcode = X86ISD::FMAX;
23800         break;
23801       case ISD::SETULE:
23802         // Converting this to a max would handle both negative zeros and NaNs
23803         // incorrectly, but we can swap the operands to fix both.
23804         std::swap(LHS, RHS);
23805       case ISD::SETOLT:
23806       case ISD::SETLT:
23807       case ISD::SETLE:
23808         Opcode = X86ISD::FMAX;
23809         break;
23810       }
23811     }
23812
23813     if (Opcode)
23814       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23815   }
23816
23817   EVT CondVT = Cond.getValueType();
23818   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23819       CondVT.getVectorElementType() == MVT::i1) {
23820     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23821     // lowering on KNL. In this case we convert it to
23822     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23823     // The same situation for all 128 and 256-bit vectors of i8 and i16.
23824     // Since SKX these selects have a proper lowering.
23825     EVT OpVT = LHS.getValueType();
23826     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23827         (OpVT.getVectorElementType() == MVT::i8 ||
23828          OpVT.getVectorElementType() == MVT::i16) &&
23829         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23830       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23831       DCI.AddToWorklist(Cond.getNode());
23832       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23833     }
23834   }
23835   // If this is a select between two integer constants, try to do some
23836   // optimizations.
23837   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23838     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23839       // Don't do this for crazy integer types.
23840       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23841         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23842         // so that TrueC (the true value) is larger than FalseC.
23843         bool NeedsCondInvert = false;
23844
23845         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23846             // Efficiently invertible.
23847             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
23848              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
23849               isa<ConstantSDNode>(Cond.getOperand(1))))) {
23850           NeedsCondInvert = true;
23851           std::swap(TrueC, FalseC);
23852         }
23853
23854         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
23855         if (FalseC->getAPIntValue() == 0 &&
23856             TrueC->getAPIntValue().isPowerOf2()) {
23857           if (NeedsCondInvert) // Invert the condition if needed.
23858             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23859                                DAG.getConstant(1, DL, Cond.getValueType()));
23860
23861           // Zero extend the condition if needed.
23862           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23863
23864           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23865           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23866                              DAG.getConstant(ShAmt, DL, MVT::i8));
23867         }
23868
23869         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23870         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23871           if (NeedsCondInvert) // Invert the condition if needed.
23872             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23873                                DAG.getConstant(1, DL, Cond.getValueType()));
23874
23875           // Zero extend the condition if needed.
23876           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23877                              FalseC->getValueType(0), Cond);
23878           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23879                              SDValue(FalseC, 0));
23880         }
23881
23882         // Optimize cases that will turn into an LEA instruction.  This requires
23883         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23884         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23885           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23886           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23887
23888           bool isFastMultiplier = false;
23889           if (Diff < 10) {
23890             switch ((unsigned char)Diff) {
23891               default: break;
23892               case 1:  // result = add base, cond
23893               case 2:  // result = lea base(    , cond*2)
23894               case 3:  // result = lea base(cond, cond*2)
23895               case 4:  // result = lea base(    , cond*4)
23896               case 5:  // result = lea base(cond, cond*4)
23897               case 8:  // result = lea base(    , cond*8)
23898               case 9:  // result = lea base(cond, cond*8)
23899                 isFastMultiplier = true;
23900                 break;
23901             }
23902           }
23903
23904           if (isFastMultiplier) {
23905             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23906             if (NeedsCondInvert) // Invert the condition if needed.
23907               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23908                                  DAG.getConstant(1, DL, Cond.getValueType()));
23909
23910             // Zero extend the condition if needed.
23911             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23912                                Cond);
23913             // Scale the condition by the difference.
23914             if (Diff != 1)
23915               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23916                                  DAG.getConstant(Diff, DL,
23917                                                  Cond.getValueType()));
23918
23919             // Add the base if non-zero.
23920             if (FalseC->getAPIntValue() != 0)
23921               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23922                                  SDValue(FalseC, 0));
23923             return Cond;
23924           }
23925         }
23926       }
23927   }
23928
23929   // Canonicalize max and min:
23930   // (x > y) ? x : y -> (x >= y) ? x : y
23931   // (x < y) ? x : y -> (x <= y) ? x : y
23932   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23933   // the need for an extra compare
23934   // against zero. e.g.
23935   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23936   // subl   %esi, %edi
23937   // testl  %edi, %edi
23938   // movl   $0, %eax
23939   // cmovgl %edi, %eax
23940   // =>
23941   // xorl   %eax, %eax
23942   // subl   %esi, $edi
23943   // cmovsl %eax, %edi
23944   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23945       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23946       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23947     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23948     switch (CC) {
23949     default: break;
23950     case ISD::SETLT:
23951     case ISD::SETGT: {
23952       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23953       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23954                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
23955       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23956     }
23957     }
23958   }
23959
23960   // Early exit check
23961   if (!TLI.isTypeLegal(VT))
23962     return SDValue();
23963
23964   // Match VSELECTs into subs with unsigned saturation.
23965   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23966       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23967       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23968        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23969     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23970
23971     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23972     // left side invert the predicate to simplify logic below.
23973     SDValue Other;
23974     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23975       Other = RHS;
23976       CC = ISD::getSetCCInverse(CC, true);
23977     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23978       Other = LHS;
23979     }
23980
23981     if (Other.getNode() && Other->getNumOperands() == 2 &&
23982         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23983       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23984       SDValue CondRHS = Cond->getOperand(1);
23985
23986       // Look for a general sub with unsigned saturation first.
23987       // x >= y ? x-y : 0 --> subus x, y
23988       // x >  y ? x-y : 0 --> subus x, y
23989       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23990           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23991         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23992
23993       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23994         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23995           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23996             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23997               // If the RHS is a constant we have to reverse the const
23998               // canonicalization.
23999               // x > C-1 ? x+-C : 0 --> subus x, C
24000               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24001                   CondRHSConst->getAPIntValue() ==
24002                       (-OpRHSConst->getAPIntValue() - 1))
24003                 return DAG.getNode(
24004                     X86ISD::SUBUS, DL, VT, OpLHS,
24005                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24006
24007           // Another special case: If C was a sign bit, the sub has been
24008           // canonicalized into a xor.
24009           // FIXME: Would it be better to use computeKnownBits to determine
24010           //        whether it's safe to decanonicalize the xor?
24011           // x s< 0 ? x^C : 0 --> subus x, C
24012           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24013               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24014               OpRHSConst->getAPIntValue().isSignBit())
24015             // Note that we have to rebuild the RHS constant here to ensure we
24016             // don't rely on particular values of undef lanes.
24017             return DAG.getNode(
24018                 X86ISD::SUBUS, DL, VT, OpLHS,
24019                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24020         }
24021     }
24022   }
24023
24024   // Simplify vector selection if condition value type matches vselect
24025   // operand type
24026   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24027     assert(Cond.getValueType().isVector() &&
24028            "vector select expects a vector selector!");
24029
24030     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24031     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24032
24033     // Try invert the condition if true value is not all 1s and false value
24034     // is not all 0s.
24035     if (!TValIsAllOnes && !FValIsAllZeros &&
24036         // Check if the selector will be produced by CMPP*/PCMP*
24037         Cond.getOpcode() == ISD::SETCC &&
24038         // Check if SETCC has already been promoted
24039         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24040             CondVT) {
24041       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24042       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24043
24044       if (TValIsAllZeros || FValIsAllOnes) {
24045         SDValue CC = Cond.getOperand(2);
24046         ISD::CondCode NewCC =
24047           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24048                                Cond.getOperand(0).getValueType().isInteger());
24049         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24050         std::swap(LHS, RHS);
24051         TValIsAllOnes = FValIsAllOnes;
24052         FValIsAllZeros = TValIsAllZeros;
24053       }
24054     }
24055
24056     if (TValIsAllOnes || FValIsAllZeros) {
24057       SDValue Ret;
24058
24059       if (TValIsAllOnes && FValIsAllZeros)
24060         Ret = Cond;
24061       else if (TValIsAllOnes)
24062         Ret =
24063             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24064       else if (FValIsAllZeros)
24065         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24066                           DAG.getBitcast(CondVT, LHS));
24067
24068       return DAG.getBitcast(VT, Ret);
24069     }
24070   }
24071
24072   // We should generate an X86ISD::BLENDI from a vselect if its argument
24073   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24074   // constants. This specific pattern gets generated when we split a
24075   // selector for a 512 bit vector in a machine without AVX512 (but with
24076   // 256-bit vectors), during legalization:
24077   //
24078   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24079   //
24080   // Iff we find this pattern and the build_vectors are built from
24081   // constants, we translate the vselect into a shuffle_vector that we
24082   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24083   if ((N->getOpcode() == ISD::VSELECT ||
24084        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24085       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24086     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24087     if (Shuffle.getNode())
24088       return Shuffle;
24089   }
24090
24091   // If this is a *dynamic* select (non-constant condition) and we can match
24092   // this node with one of the variable blend instructions, restructure the
24093   // condition so that the blends can use the high bit of each element and use
24094   // SimplifyDemandedBits to simplify the condition operand.
24095   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24096       !DCI.isBeforeLegalize() &&
24097       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24098     unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24099
24100     // Don't optimize vector selects that map to mask-registers.
24101     if (BitWidth == 1)
24102       return SDValue();
24103
24104     // We can only handle the cases where VSELECT is directly legal on the
24105     // subtarget. We custom lower VSELECT nodes with constant conditions and
24106     // this makes it hard to see whether a dynamic VSELECT will correctly
24107     // lower, so we both check the operation's status and explicitly handle the
24108     // cases where a *dynamic* blend will fail even though a constant-condition
24109     // blend could be custom lowered.
24110     // FIXME: We should find a better way to handle this class of problems.
24111     // Potentially, we should combine constant-condition vselect nodes
24112     // pre-legalization into shuffles and not mark as many types as custom
24113     // lowered.
24114     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24115       return SDValue();
24116     // FIXME: We don't support i16-element blends currently. We could and
24117     // should support them by making *all* the bits in the condition be set
24118     // rather than just the high bit and using an i8-element blend.
24119     if (VT.getVectorElementType() == MVT::i16)
24120       return SDValue();
24121     // Dynamic blending was only available from SSE4.1 onward.
24122     if (VT.is128BitVector() && !Subtarget->hasSSE41())
24123       return SDValue();
24124     // Byte blends are only available in AVX2
24125     if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24126       return SDValue();
24127
24128     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24129     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24130
24131     APInt KnownZero, KnownOne;
24132     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24133                                           DCI.isBeforeLegalizeOps());
24134     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24135         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24136                                  TLO)) {
24137       // If we changed the computation somewhere in the DAG, this change
24138       // will affect all users of Cond.
24139       // Make sure it is fine and update all the nodes so that we do not
24140       // use the generic VSELECT anymore. Otherwise, we may perform
24141       // wrong optimizations as we messed up with the actual expectation
24142       // for the vector boolean values.
24143       if (Cond != TLO.Old) {
24144         // Check all uses of that condition operand to check whether it will be
24145         // consumed by non-BLEND instructions, which may depend on all bits are
24146         // set properly.
24147         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24148              I != E; ++I)
24149           if (I->getOpcode() != ISD::VSELECT)
24150             // TODO: Add other opcodes eventually lowered into BLEND.
24151             return SDValue();
24152
24153         // Update all the users of the condition, before committing the change,
24154         // so that the VSELECT optimizations that expect the correct vector
24155         // boolean value will not be triggered.
24156         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24157              I != E; ++I)
24158           DAG.ReplaceAllUsesOfValueWith(
24159               SDValue(*I, 0),
24160               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24161                           Cond, I->getOperand(1), I->getOperand(2)));
24162         DCI.CommitTargetLoweringOpt(TLO);
24163         return SDValue();
24164       }
24165       // At this point, only Cond is changed. Change the condition
24166       // just for N to keep the opportunity to optimize all other
24167       // users their own way.
24168       DAG.ReplaceAllUsesOfValueWith(
24169           SDValue(N, 0),
24170           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24171                       TLO.New, N->getOperand(1), N->getOperand(2)));
24172       return SDValue();
24173     }
24174   }
24175
24176   return SDValue();
24177 }
24178
24179 // Check whether a boolean test is testing a boolean value generated by
24180 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24181 // code.
24182 //
24183 // Simplify the following patterns:
24184 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24185 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24186 // to (Op EFLAGS Cond)
24187 //
24188 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24189 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24190 // to (Op EFLAGS !Cond)
24191 //
24192 // where Op could be BRCOND or CMOV.
24193 //
24194 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24195   // Quit if not CMP and SUB with its value result used.
24196   if (Cmp.getOpcode() != X86ISD::CMP &&
24197       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24198       return SDValue();
24199
24200   // Quit if not used as a boolean value.
24201   if (CC != X86::COND_E && CC != X86::COND_NE)
24202     return SDValue();
24203
24204   // Check CMP operands. One of them should be 0 or 1 and the other should be
24205   // an SetCC or extended from it.
24206   SDValue Op1 = Cmp.getOperand(0);
24207   SDValue Op2 = Cmp.getOperand(1);
24208
24209   SDValue SetCC;
24210   const ConstantSDNode* C = nullptr;
24211   bool needOppositeCond = (CC == X86::COND_E);
24212   bool checkAgainstTrue = false; // Is it a comparison against 1?
24213
24214   if ((C = dyn_cast<ConstantSDNode>(Op1)))
24215     SetCC = Op2;
24216   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24217     SetCC = Op1;
24218   else // Quit if all operands are not constants.
24219     return SDValue();
24220
24221   if (C->getZExtValue() == 1) {
24222     needOppositeCond = !needOppositeCond;
24223     checkAgainstTrue = true;
24224   } else if (C->getZExtValue() != 0)
24225     // Quit if the constant is neither 0 or 1.
24226     return SDValue();
24227
24228   bool truncatedToBoolWithAnd = false;
24229   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24230   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24231          SetCC.getOpcode() == ISD::TRUNCATE ||
24232          SetCC.getOpcode() == ISD::AND) {
24233     if (SetCC.getOpcode() == ISD::AND) {
24234       int OpIdx = -1;
24235       ConstantSDNode *CS;
24236       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
24237           CS->getZExtValue() == 1)
24238         OpIdx = 1;
24239       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
24240           CS->getZExtValue() == 1)
24241         OpIdx = 0;
24242       if (OpIdx == -1)
24243         break;
24244       SetCC = SetCC.getOperand(OpIdx);
24245       truncatedToBoolWithAnd = true;
24246     } else
24247       SetCC = SetCC.getOperand(0);
24248   }
24249
24250   switch (SetCC.getOpcode()) {
24251   case X86ISD::SETCC_CARRY:
24252     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24253     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24254     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24255     // truncated to i1 using 'and'.
24256     if (checkAgainstTrue && !truncatedToBoolWithAnd)
24257       break;
24258     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24259            "Invalid use of SETCC_CARRY!");
24260     // FALL THROUGH
24261   case X86ISD::SETCC:
24262     // Set the condition code or opposite one if necessary.
24263     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24264     if (needOppositeCond)
24265       CC = X86::GetOppositeBranchCondition(CC);
24266     return SetCC.getOperand(1);
24267   case X86ISD::CMOV: {
24268     // Check whether false/true value has canonical one, i.e. 0 or 1.
24269     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24270     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24271     // Quit if true value is not a constant.
24272     if (!TVal)
24273       return SDValue();
24274     // Quit if false value is not a constant.
24275     if (!FVal) {
24276       SDValue Op = SetCC.getOperand(0);
24277       // Skip 'zext' or 'trunc' node.
24278       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24279           Op.getOpcode() == ISD::TRUNCATE)
24280         Op = Op.getOperand(0);
24281       // A special case for rdrand/rdseed, where 0 is set if false cond is
24282       // found.
24283       if ((Op.getOpcode() != X86ISD::RDRAND &&
24284            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24285         return SDValue();
24286     }
24287     // Quit if false value is not the constant 0 or 1.
24288     bool FValIsFalse = true;
24289     if (FVal && FVal->getZExtValue() != 0) {
24290       if (FVal->getZExtValue() != 1)
24291         return SDValue();
24292       // If FVal is 1, opposite cond is needed.
24293       needOppositeCond = !needOppositeCond;
24294       FValIsFalse = false;
24295     }
24296     // Quit if TVal is not the constant opposite of FVal.
24297     if (FValIsFalse && TVal->getZExtValue() != 1)
24298       return SDValue();
24299     if (!FValIsFalse && TVal->getZExtValue() != 0)
24300       return SDValue();
24301     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24302     if (needOppositeCond)
24303       CC = X86::GetOppositeBranchCondition(CC);
24304     return SetCC.getOperand(3);
24305   }
24306   }
24307
24308   return SDValue();
24309 }
24310
24311 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24312 /// Match:
24313 ///   (X86or (X86setcc) (X86setcc))
24314 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
24315 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24316                                            X86::CondCode &CC1, SDValue &Flags,
24317                                            bool &isAnd) {
24318   if (Cond->getOpcode() == X86ISD::CMP) {
24319     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
24320     if (!CondOp1C || !CondOp1C->isNullValue())
24321       return false;
24322
24323     Cond = Cond->getOperand(0);
24324   }
24325
24326   isAnd = false;
24327
24328   SDValue SetCC0, SetCC1;
24329   switch (Cond->getOpcode()) {
24330   default: return false;
24331   case ISD::AND:
24332   case X86ISD::AND:
24333     isAnd = true;
24334     // fallthru
24335   case ISD::OR:
24336   case X86ISD::OR:
24337     SetCC0 = Cond->getOperand(0);
24338     SetCC1 = Cond->getOperand(1);
24339     break;
24340   };
24341
24342   // Make sure we have SETCC nodes, using the same flags value.
24343   if (SetCC0.getOpcode() != X86ISD::SETCC ||
24344       SetCC1.getOpcode() != X86ISD::SETCC ||
24345       SetCC0->getOperand(1) != SetCC1->getOperand(1))
24346     return false;
24347
24348   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24349   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24350   Flags = SetCC0->getOperand(1);
24351   return true;
24352 }
24353
24354 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24355 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24356                                   TargetLowering::DAGCombinerInfo &DCI,
24357                                   const X86Subtarget *Subtarget) {
24358   SDLoc DL(N);
24359
24360   // If the flag operand isn't dead, don't touch this CMOV.
24361   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24362     return SDValue();
24363
24364   SDValue FalseOp = N->getOperand(0);
24365   SDValue TrueOp = N->getOperand(1);
24366   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24367   SDValue Cond = N->getOperand(3);
24368
24369   if (CC == X86::COND_E || CC == X86::COND_NE) {
24370     switch (Cond.getOpcode()) {
24371     default: break;
24372     case X86ISD::BSR:
24373     case X86ISD::BSF:
24374       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24375       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24376         return (CC == X86::COND_E) ? FalseOp : TrueOp;
24377     }
24378   }
24379
24380   SDValue Flags;
24381
24382   Flags = checkBoolTestSetCCCombine(Cond, CC);
24383   if (Flags.getNode() &&
24384       // Extra check as FCMOV only supports a subset of X86 cond.
24385       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24386     SDValue Ops[] = { FalseOp, TrueOp,
24387                       DAG.getConstant(CC, DL, MVT::i8), Flags };
24388     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24389   }
24390
24391   // If this is a select between two integer constants, try to do some
24392   // optimizations.  Note that the operands are ordered the opposite of SELECT
24393   // operands.
24394   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24395     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24396       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24397       // larger than FalseC (the false value).
24398       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24399         CC = X86::GetOppositeBranchCondition(CC);
24400         std::swap(TrueC, FalseC);
24401         std::swap(TrueOp, FalseOp);
24402       }
24403
24404       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
24405       // This is efficient for any integer data type (including i8/i16) and
24406       // shift amount.
24407       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24408         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24409                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24410
24411         // Zero extend the condition if needed.
24412         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24413
24414         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24415         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24416                            DAG.getConstant(ShAmt, DL, MVT::i8));
24417         if (N->getNumValues() == 2)  // Dead flag value?
24418           return DCI.CombineTo(N, Cond, SDValue());
24419         return Cond;
24420       }
24421
24422       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
24423       // for any integer data type, including i8/i16.
24424       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24425         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24426                            DAG.getConstant(CC, DL, MVT::i8), Cond);
24427
24428         // Zero extend the condition if needed.
24429         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24430                            FalseC->getValueType(0), Cond);
24431         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24432                            SDValue(FalseC, 0));
24433
24434         if (N->getNumValues() == 2)  // Dead flag value?
24435           return DCI.CombineTo(N, Cond, SDValue());
24436         return Cond;
24437       }
24438
24439       // Optimize cases that will turn into an LEA instruction.  This requires
24440       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24441       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24442         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24443         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24444
24445         bool isFastMultiplier = false;
24446         if (Diff < 10) {
24447           switch ((unsigned char)Diff) {
24448           default: break;
24449           case 1:  // result = add base, cond
24450           case 2:  // result = lea base(    , cond*2)
24451           case 3:  // result = lea base(cond, cond*2)
24452           case 4:  // result = lea base(    , cond*4)
24453           case 5:  // result = lea base(cond, cond*4)
24454           case 8:  // result = lea base(    , cond*8)
24455           case 9:  // result = lea base(cond, cond*8)
24456             isFastMultiplier = true;
24457             break;
24458           }
24459         }
24460
24461         if (isFastMultiplier) {
24462           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24463           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24464                              DAG.getConstant(CC, DL, MVT::i8), Cond);
24465           // Zero extend the condition if needed.
24466           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24467                              Cond);
24468           // Scale the condition by the difference.
24469           if (Diff != 1)
24470             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24471                                DAG.getConstant(Diff, DL, Cond.getValueType()));
24472
24473           // Add the base if non-zero.
24474           if (FalseC->getAPIntValue() != 0)
24475             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24476                                SDValue(FalseC, 0));
24477           if (N->getNumValues() == 2)  // Dead flag value?
24478             return DCI.CombineTo(N, Cond, SDValue());
24479           return Cond;
24480         }
24481       }
24482     }
24483   }
24484
24485   // Handle these cases:
24486   //   (select (x != c), e, c) -> select (x != c), e, x),
24487   //   (select (x == c), c, e) -> select (x == c), x, e)
24488   // where the c is an integer constant, and the "select" is the combination
24489   // of CMOV and CMP.
24490   //
24491   // The rationale for this change is that the conditional-move from a constant
24492   // needs two instructions, however, conditional-move from a register needs
24493   // only one instruction.
24494   //
24495   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24496   //  some instruction-combining opportunities. This opt needs to be
24497   //  postponed as late as possible.
24498   //
24499   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24500     // the DCI.xxxx conditions are provided to postpone the optimization as
24501     // late as possible.
24502
24503     ConstantSDNode *CmpAgainst = nullptr;
24504     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24505         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24506         !isa<ConstantSDNode>(Cond.getOperand(0))) {
24507
24508       if (CC == X86::COND_NE &&
24509           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24510         CC = X86::GetOppositeBranchCondition(CC);
24511         std::swap(TrueOp, FalseOp);
24512       }
24513
24514       if (CC == X86::COND_E &&
24515           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24516         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24517                           DAG.getConstant(CC, DL, MVT::i8), Cond };
24518         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24519       }
24520     }
24521   }
24522
24523   // Fold and/or of setcc's to double CMOV:
24524   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24525   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24526   //
24527   // This combine lets us generate:
24528   //   cmovcc1 (jcc1 if we don't have CMOV)
24529   //   cmovcc2 (same)
24530   // instead of:
24531   //   setcc1
24532   //   setcc2
24533   //   and/or
24534   //   cmovne (jne if we don't have CMOV)
24535   // When we can't use the CMOV instruction, it might increase branch
24536   // mispredicts.
24537   // When we can use CMOV, or when there is no mispredict, this improves
24538   // throughput and reduces register pressure.
24539   //
24540   if (CC == X86::COND_NE) {
24541     SDValue Flags;
24542     X86::CondCode CC0, CC1;
24543     bool isAndSetCC;
24544     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24545       if (isAndSetCC) {
24546         std::swap(FalseOp, TrueOp);
24547         CC0 = X86::GetOppositeBranchCondition(CC0);
24548         CC1 = X86::GetOppositeBranchCondition(CC1);
24549       }
24550
24551       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24552         Flags};
24553       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24554       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24555       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24556       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24557       return CMOV;
24558     }
24559   }
24560
24561   return SDValue();
24562 }
24563
24564 /// PerformMulCombine - Optimize a single multiply with constant into two
24565 /// in order to implement it with two cheaper instructions, e.g.
24566 /// LEA + SHL, LEA + LEA.
24567 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24568                                  TargetLowering::DAGCombinerInfo &DCI) {
24569   // An imul is usually smaller than the alternative sequence.
24570   if (DAG.getMachineFunction().getFunction()->optForMinSize())
24571     return SDValue();
24572
24573   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24574     return SDValue();
24575
24576   EVT VT = N->getValueType(0);
24577   if (VT != MVT::i64 && VT != MVT::i32)
24578     return SDValue();
24579
24580   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24581   if (!C)
24582     return SDValue();
24583   uint64_t MulAmt = C->getZExtValue();
24584   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24585     return SDValue();
24586
24587   uint64_t MulAmt1 = 0;
24588   uint64_t MulAmt2 = 0;
24589   if ((MulAmt % 9) == 0) {
24590     MulAmt1 = 9;
24591     MulAmt2 = MulAmt / 9;
24592   } else if ((MulAmt % 5) == 0) {
24593     MulAmt1 = 5;
24594     MulAmt2 = MulAmt / 5;
24595   } else if ((MulAmt % 3) == 0) {
24596     MulAmt1 = 3;
24597     MulAmt2 = MulAmt / 3;
24598   }
24599   if (MulAmt2 &&
24600       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24601     SDLoc DL(N);
24602
24603     if (isPowerOf2_64(MulAmt2) &&
24604         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24605       // If second multiplifer is pow2, issue it first. We want the multiply by
24606       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24607       // is an add.
24608       std::swap(MulAmt1, MulAmt2);
24609
24610     SDValue NewMul;
24611     if (isPowerOf2_64(MulAmt1))
24612       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24613                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24614     else
24615       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24616                            DAG.getConstant(MulAmt1, DL, VT));
24617
24618     if (isPowerOf2_64(MulAmt2))
24619       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24620                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24621     else
24622       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24623                            DAG.getConstant(MulAmt2, DL, VT));
24624
24625     // Do not add new nodes to DAG combiner worklist.
24626     DCI.CombineTo(N, NewMul, false);
24627   }
24628   return SDValue();
24629 }
24630
24631 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24632   SDValue N0 = N->getOperand(0);
24633   SDValue N1 = N->getOperand(1);
24634   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24635   EVT VT = N0.getValueType();
24636
24637   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24638   // since the result of setcc_c is all zero's or all ones.
24639   if (VT.isInteger() && !VT.isVector() &&
24640       N1C && N0.getOpcode() == ISD::AND &&
24641       N0.getOperand(1).getOpcode() == ISD::Constant) {
24642     SDValue N00 = N0.getOperand(0);
24643     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24644     APInt ShAmt = N1C->getAPIntValue();
24645     Mask = Mask.shl(ShAmt);
24646     bool MaskOK = false;
24647     // We can handle cases concerning bit-widening nodes containing setcc_c if
24648     // we carefully interrogate the mask to make sure we are semantics
24649     // preserving.
24650     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24651     // of the underlying setcc_c operation if the setcc_c was zero extended.
24652     // Consider the following example:
24653     //   zext(setcc_c)                 -> i32 0x0000FFFF
24654     //   c1                            -> i32 0x0000FFFF
24655     //   c2                            -> i32 0x00000001
24656     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24657     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
24658     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24659       MaskOK = true;
24660     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24661                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24662       MaskOK = true;
24663     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24664                 N00.getOpcode() == ISD::ANY_EXTEND) &&
24665                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24666       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24667     }
24668     if (MaskOK && Mask != 0) {
24669       SDLoc DL(N);
24670       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24671     }
24672   }
24673
24674   // Hardware support for vector shifts is sparse which makes us scalarize the
24675   // vector operations in many cases. Also, on sandybridge ADD is faster than
24676   // shl.
24677   // (shl V, 1) -> add V,V
24678   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24679     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24680       assert(N0.getValueType().isVector() && "Invalid vector shift type");
24681       // We shift all of the values by one. In many cases we do not have
24682       // hardware support for this operation. This is better expressed as an ADD
24683       // of two values.
24684       if (N1SplatC->getAPIntValue() == 1)
24685         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24686     }
24687
24688   return SDValue();
24689 }
24690
24691 /// \brief Returns a vector of 0s if the node in input is a vector logical
24692 /// shift by a constant amount which is known to be bigger than or equal
24693 /// to the vector element size in bits.
24694 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24695                                       const X86Subtarget *Subtarget) {
24696   EVT VT = N->getValueType(0);
24697
24698   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24699       (!Subtarget->hasInt256() ||
24700        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24701     return SDValue();
24702
24703   SDValue Amt = N->getOperand(1);
24704   SDLoc DL(N);
24705   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24706     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24707       APInt ShiftAmt = AmtSplat->getAPIntValue();
24708       unsigned MaxAmount =
24709         VT.getSimpleVT().getVectorElementType().getSizeInBits();
24710
24711       // SSE2/AVX2 logical shifts always return a vector of 0s
24712       // if the shift amount is bigger than or equal to
24713       // the element size. The constant shift amount will be
24714       // encoded as a 8-bit immediate.
24715       if (ShiftAmt.trunc(8).uge(MaxAmount))
24716         return getZeroVector(VT, Subtarget, DAG, DL);
24717     }
24718
24719   return SDValue();
24720 }
24721
24722 /// PerformShiftCombine - Combine shifts.
24723 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24724                                    TargetLowering::DAGCombinerInfo &DCI,
24725                                    const X86Subtarget *Subtarget) {
24726   if (N->getOpcode() == ISD::SHL)
24727     if (SDValue V = PerformSHLCombine(N, DAG))
24728       return V;
24729
24730   // Try to fold this logical shift into a zero vector.
24731   if (N->getOpcode() != ISD::SRA)
24732     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24733       return V;
24734
24735   return SDValue();
24736 }
24737
24738 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
24739 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24740 // and friends.  Likewise for OR -> CMPNEQSS.
24741 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24742                             TargetLowering::DAGCombinerInfo &DCI,
24743                             const X86Subtarget *Subtarget) {
24744   unsigned opcode;
24745
24746   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24747   // we're requiring SSE2 for both.
24748   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24749     SDValue N0 = N->getOperand(0);
24750     SDValue N1 = N->getOperand(1);
24751     SDValue CMP0 = N0->getOperand(1);
24752     SDValue CMP1 = N1->getOperand(1);
24753     SDLoc DL(N);
24754
24755     // The SETCCs should both refer to the same CMP.
24756     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24757       return SDValue();
24758
24759     SDValue CMP00 = CMP0->getOperand(0);
24760     SDValue CMP01 = CMP0->getOperand(1);
24761     EVT     VT    = CMP00.getValueType();
24762
24763     if (VT == MVT::f32 || VT == MVT::f64) {
24764       bool ExpectingFlags = false;
24765       // Check for any users that want flags:
24766       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24767            !ExpectingFlags && UI != UE; ++UI)
24768         switch (UI->getOpcode()) {
24769         default:
24770         case ISD::BR_CC:
24771         case ISD::BRCOND:
24772         case ISD::SELECT:
24773           ExpectingFlags = true;
24774           break;
24775         case ISD::CopyToReg:
24776         case ISD::SIGN_EXTEND:
24777         case ISD::ZERO_EXTEND:
24778         case ISD::ANY_EXTEND:
24779           break;
24780         }
24781
24782       if (!ExpectingFlags) {
24783         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24784         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24785
24786         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24787           X86::CondCode tmp = cc0;
24788           cc0 = cc1;
24789           cc1 = tmp;
24790         }
24791
24792         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
24793             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24794           // FIXME: need symbolic constants for these magic numbers.
24795           // See X86ATTInstPrinter.cpp:printSSECC().
24796           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24797           if (Subtarget->hasAVX512()) {
24798             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24799                                          CMP01,
24800                                          DAG.getConstant(x86cc, DL, MVT::i8));
24801             if (N->getValueType(0) != MVT::i1)
24802               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24803                                  FSetCC);
24804             return FSetCC;
24805           }
24806           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24807                                               CMP00.getValueType(), CMP00, CMP01,
24808                                               DAG.getConstant(x86cc, DL,
24809                                                               MVT::i8));
24810
24811           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24812           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24813
24814           if (is64BitFP && !Subtarget->is64Bit()) {
24815             // On a 32-bit target, we cannot bitcast the 64-bit float to a
24816             // 64-bit integer, since that's not a legal type. Since
24817             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24818             // bits, but can do this little dance to extract the lowest 32 bits
24819             // and work with those going forward.
24820             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24821                                            OnesOrZeroesF);
24822             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24823             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24824                                         Vector32, DAG.getIntPtrConstant(0, DL));
24825             IntVT = MVT::i32;
24826           }
24827
24828           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24829           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24830                                       DAG.getConstant(1, DL, IntVT));
24831           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24832                                               ANDed);
24833           return OneBitOfTruth;
24834         }
24835       }
24836     }
24837   }
24838   return SDValue();
24839 }
24840
24841 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24842 /// so it can be folded inside ANDNP.
24843 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24844   EVT VT = N->getValueType(0);
24845
24846   // Match direct AllOnes for 128 and 256-bit vectors
24847   if (ISD::isBuildVectorAllOnes(N))
24848     return true;
24849
24850   // Look through a bit convert.
24851   if (N->getOpcode() == ISD::BITCAST)
24852     N = N->getOperand(0).getNode();
24853
24854   // Sometimes the operand may come from a insert_subvector building a 256-bit
24855   // allones vector
24856   if (VT.is256BitVector() &&
24857       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24858     SDValue V1 = N->getOperand(0);
24859     SDValue V2 = N->getOperand(1);
24860
24861     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24862         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24863         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24864         ISD::isBuildVectorAllOnes(V2.getNode()))
24865       return true;
24866   }
24867
24868   return false;
24869 }
24870
24871 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24872 // register. In most cases we actually compare or select YMM-sized registers
24873 // and mixing the two types creates horrible code. This method optimizes
24874 // some of the transition sequences.
24875 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24876                                  TargetLowering::DAGCombinerInfo &DCI,
24877                                  const X86Subtarget *Subtarget) {
24878   EVT VT = N->getValueType(0);
24879   if (!VT.is256BitVector())
24880     return SDValue();
24881
24882   assert((N->getOpcode() == ISD::ANY_EXTEND ||
24883           N->getOpcode() == ISD::ZERO_EXTEND ||
24884           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24885
24886   SDValue Narrow = N->getOperand(0);
24887   EVT NarrowVT = Narrow->getValueType(0);
24888   if (!NarrowVT.is128BitVector())
24889     return SDValue();
24890
24891   if (Narrow->getOpcode() != ISD::XOR &&
24892       Narrow->getOpcode() != ISD::AND &&
24893       Narrow->getOpcode() != ISD::OR)
24894     return SDValue();
24895
24896   SDValue N0  = Narrow->getOperand(0);
24897   SDValue N1  = Narrow->getOperand(1);
24898   SDLoc DL(Narrow);
24899
24900   // The Left side has to be a trunc.
24901   if (N0.getOpcode() != ISD::TRUNCATE)
24902     return SDValue();
24903
24904   // The type of the truncated inputs.
24905   EVT WideVT = N0->getOperand(0)->getValueType(0);
24906   if (WideVT != VT)
24907     return SDValue();
24908
24909   // The right side has to be a 'trunc' or a constant vector.
24910   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24911   ConstantSDNode *RHSConstSplat = nullptr;
24912   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24913     RHSConstSplat = RHSBV->getConstantSplatNode();
24914   if (!RHSTrunc && !RHSConstSplat)
24915     return SDValue();
24916
24917   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24918
24919   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24920     return SDValue();
24921
24922   // Set N0 and N1 to hold the inputs to the new wide operation.
24923   N0 = N0->getOperand(0);
24924   if (RHSConstSplat) {
24925     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
24926                      SDValue(RHSConstSplat, 0));
24927     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24928     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24929   } else if (RHSTrunc) {
24930     N1 = N1->getOperand(0);
24931   }
24932
24933   // Generate the wide operation.
24934   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24935   unsigned Opcode = N->getOpcode();
24936   switch (Opcode) {
24937   case ISD::ANY_EXTEND:
24938     return Op;
24939   case ISD::ZERO_EXTEND: {
24940     unsigned InBits = NarrowVT.getScalarSizeInBits();
24941     APInt Mask = APInt::getAllOnesValue(InBits);
24942     Mask = Mask.zext(VT.getScalarSizeInBits());
24943     return DAG.getNode(ISD::AND, DL, VT,
24944                        Op, DAG.getConstant(Mask, DL, VT));
24945   }
24946   case ISD::SIGN_EXTEND:
24947     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24948                        Op, DAG.getValueType(NarrowVT));
24949   default:
24950     llvm_unreachable("Unexpected opcode");
24951   }
24952 }
24953
24954 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24955                                  TargetLowering::DAGCombinerInfo &DCI,
24956                                  const X86Subtarget *Subtarget) {
24957   SDValue N0 = N->getOperand(0);
24958   SDValue N1 = N->getOperand(1);
24959   SDLoc DL(N);
24960
24961   // A vector zext_in_reg may be represented as a shuffle,
24962   // feeding into a bitcast (this represents anyext) feeding into
24963   // an and with a mask.
24964   // We'd like to try to combine that into a shuffle with zero
24965   // plus a bitcast, removing the and.
24966   if (N0.getOpcode() != ISD::BITCAST ||
24967       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24968     return SDValue();
24969
24970   // The other side of the AND should be a splat of 2^C, where C
24971   // is the number of bits in the source type.
24972   if (N1.getOpcode() == ISD::BITCAST)
24973     N1 = N1.getOperand(0);
24974   if (N1.getOpcode() != ISD::BUILD_VECTOR)
24975     return SDValue();
24976   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24977
24978   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24979   EVT SrcType = Shuffle->getValueType(0);
24980
24981   // We expect a single-source shuffle
24982   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24983     return SDValue();
24984
24985   unsigned SrcSize = SrcType.getScalarSizeInBits();
24986
24987   APInt SplatValue, SplatUndef;
24988   unsigned SplatBitSize;
24989   bool HasAnyUndefs;
24990   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24991                                 SplatBitSize, HasAnyUndefs))
24992     return SDValue();
24993
24994   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24995   // Make sure the splat matches the mask we expect
24996   if (SplatBitSize > ResSize ||
24997       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24998     return SDValue();
24999
25000   // Make sure the input and output size make sense
25001   if (SrcSize >= ResSize || ResSize % SrcSize)
25002     return SDValue();
25003
25004   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25005   // The number of u's between each two values depends on the ratio between
25006   // the source and dest type.
25007   unsigned ZextRatio = ResSize / SrcSize;
25008   bool IsZext = true;
25009   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25010     if (i % ZextRatio) {
25011       if (Shuffle->getMaskElt(i) > 0) {
25012         // Expected undef
25013         IsZext = false;
25014         break;
25015       }
25016     } else {
25017       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25018         // Expected element number
25019         IsZext = false;
25020         break;
25021       }
25022     }
25023   }
25024
25025   if (!IsZext)
25026     return SDValue();
25027
25028   // Ok, perform the transformation - replace the shuffle with
25029   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25030   // (instead of undef) where the k elements come from the zero vector.
25031   SmallVector<int, 8> Mask;
25032   unsigned NumElems = SrcType.getVectorNumElements();
25033   for (unsigned i = 0; i < NumElems; ++i)
25034     if (i % ZextRatio)
25035       Mask.push_back(NumElems);
25036     else
25037       Mask.push_back(i / ZextRatio);
25038
25039   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25040     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25041   return DAG.getBitcast(N0.getValueType(), NewShuffle);
25042 }
25043
25044 /// If both input operands of a logic op are being cast from floating point
25045 /// types, try to convert this into a floating point logic node to avoid
25046 /// unnecessary moves from SSE to integer registers.
25047 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25048                                         const X86Subtarget *Subtarget) {
25049   unsigned FPOpcode = ISD::DELETED_NODE;
25050   if (N->getOpcode() == ISD::AND)
25051     FPOpcode = X86ISD::FAND;
25052   else if (N->getOpcode() == ISD::OR)
25053     FPOpcode = X86ISD::FOR;
25054   else if (N->getOpcode() == ISD::XOR)
25055     FPOpcode = X86ISD::FXOR;
25056
25057   assert(FPOpcode != ISD::DELETED_NODE &&
25058          "Unexpected input node for FP logic conversion");
25059
25060   EVT VT = N->getValueType(0);
25061   SDValue N0 = N->getOperand(0);
25062   SDValue N1 = N->getOperand(1);
25063   SDLoc DL(N);
25064   if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25065       ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25066        (Subtarget->hasSSE2() && VT == MVT::i64))) {
25067     SDValue N00 = N0.getOperand(0);
25068     SDValue N10 = N1.getOperand(0);
25069     EVT N00Type = N00.getValueType();
25070     EVT N10Type = N10.getValueType();
25071     if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25072       SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25073       return DAG.getBitcast(VT, FPLogic);
25074     }
25075   }
25076   return SDValue();
25077 }
25078
25079 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25080                                  TargetLowering::DAGCombinerInfo &DCI,
25081                                  const X86Subtarget *Subtarget) {
25082   if (DCI.isBeforeLegalizeOps())
25083     return SDValue();
25084
25085   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25086     return Zext;
25087
25088   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25089     return R;
25090
25091   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25092     return FPLogic;
25093
25094   EVT VT = N->getValueType(0);
25095   SDValue N0 = N->getOperand(0);
25096   SDValue N1 = N->getOperand(1);
25097   SDLoc DL(N);
25098
25099   // Create BEXTR instructions
25100   // BEXTR is ((X >> imm) & (2**size-1))
25101   if (VT == MVT::i32 || VT == MVT::i64) {
25102     // Check for BEXTR.
25103     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25104         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25105       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25106       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25107       if (MaskNode && ShiftNode) {
25108         uint64_t Mask = MaskNode->getZExtValue();
25109         uint64_t Shift = ShiftNode->getZExtValue();
25110         if (isMask_64(Mask)) {
25111           uint64_t MaskSize = countPopulation(Mask);
25112           if (Shift + MaskSize <= VT.getSizeInBits())
25113             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25114                                DAG.getConstant(Shift | (MaskSize << 8), DL,
25115                                                VT));
25116         }
25117       }
25118     } // BEXTR
25119
25120     return SDValue();
25121   }
25122
25123   // Want to form ANDNP nodes:
25124   // 1) In the hopes of then easily combining them with OR and AND nodes
25125   //    to form PBLEND/PSIGN.
25126   // 2) To match ANDN packed intrinsics
25127   if (VT != MVT::v2i64 && VT != MVT::v4i64)
25128     return SDValue();
25129
25130   // Check LHS for vnot
25131   if (N0.getOpcode() == ISD::XOR &&
25132       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25133       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25134     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25135
25136   // Check RHS for vnot
25137   if (N1.getOpcode() == ISD::XOR &&
25138       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25139       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25140     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25141
25142   return SDValue();
25143 }
25144
25145 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25146                                 TargetLowering::DAGCombinerInfo &DCI,
25147                                 const X86Subtarget *Subtarget) {
25148   if (DCI.isBeforeLegalizeOps())
25149     return SDValue();
25150
25151   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25152     return R;
25153
25154   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25155     return FPLogic;
25156
25157   SDValue N0 = N->getOperand(0);
25158   SDValue N1 = N->getOperand(1);
25159   EVT VT = N->getValueType(0);
25160
25161   // look for psign/blend
25162   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25163     if (!Subtarget->hasSSSE3() ||
25164         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25165       return SDValue();
25166
25167     // Canonicalize pandn to RHS
25168     if (N0.getOpcode() == X86ISD::ANDNP)
25169       std::swap(N0, N1);
25170     // or (and (m, y), (pandn m, x))
25171     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25172       SDValue Mask = N1.getOperand(0);
25173       SDValue X    = N1.getOperand(1);
25174       SDValue Y;
25175       if (N0.getOperand(0) == Mask)
25176         Y = N0.getOperand(1);
25177       if (N0.getOperand(1) == Mask)
25178         Y = N0.getOperand(0);
25179
25180       // Check to see if the mask appeared in both the AND and ANDNP and
25181       if (!Y.getNode())
25182         return SDValue();
25183
25184       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25185       // Look through mask bitcast.
25186       if (Mask.getOpcode() == ISD::BITCAST)
25187         Mask = Mask.getOperand(0);
25188       if (X.getOpcode() == ISD::BITCAST)
25189         X = X.getOperand(0);
25190       if (Y.getOpcode() == ISD::BITCAST)
25191         Y = Y.getOperand(0);
25192
25193       EVT MaskVT = Mask.getValueType();
25194
25195       // Validate that the Mask operand is a vector sra node.
25196       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25197       // there is no psrai.b
25198       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25199       unsigned SraAmt = ~0;
25200       if (Mask.getOpcode() == ISD::SRA) {
25201         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25202           if (auto *AmtConst = AmtBV->getConstantSplatNode())
25203             SraAmt = AmtConst->getZExtValue();
25204       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25205         SDValue SraC = Mask.getOperand(1);
25206         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
25207       }
25208       if ((SraAmt + 1) != EltBits)
25209         return SDValue();
25210
25211       SDLoc DL(N);
25212
25213       // Now we know we at least have a plendvb with the mask val.  See if
25214       // we can form a psignb/w/d.
25215       // psign = x.type == y.type == mask.type && y = sub(0, x);
25216       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25217           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25218           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25219         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25220                "Unsupported VT for PSIGN");
25221         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25222         return DAG.getBitcast(VT, Mask);
25223       }
25224       // PBLENDVB only available on SSE 4.1
25225       if (!Subtarget->hasSSE41())
25226         return SDValue();
25227
25228       MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25229
25230       X = DAG.getBitcast(BlendVT, X);
25231       Y = DAG.getBitcast(BlendVT, Y);
25232       Mask = DAG.getBitcast(BlendVT, Mask);
25233       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25234       return DAG.getBitcast(VT, Mask);
25235     }
25236   }
25237
25238   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25239     return SDValue();
25240
25241   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25242   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25243
25244   // SHLD/SHRD instructions have lower register pressure, but on some
25245   // platforms they have higher latency than the equivalent
25246   // series of shifts/or that would otherwise be generated.
25247   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25248   // have higher latencies and we are not optimizing for size.
25249   if (!OptForSize && Subtarget->isSHLDSlow())
25250     return SDValue();
25251
25252   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25253     std::swap(N0, N1);
25254   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25255     return SDValue();
25256   if (!N0.hasOneUse() || !N1.hasOneUse())
25257     return SDValue();
25258
25259   SDValue ShAmt0 = N0.getOperand(1);
25260   if (ShAmt0.getValueType() != MVT::i8)
25261     return SDValue();
25262   SDValue ShAmt1 = N1.getOperand(1);
25263   if (ShAmt1.getValueType() != MVT::i8)
25264     return SDValue();
25265   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25266     ShAmt0 = ShAmt0.getOperand(0);
25267   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25268     ShAmt1 = ShAmt1.getOperand(0);
25269
25270   SDLoc DL(N);
25271   unsigned Opc = X86ISD::SHLD;
25272   SDValue Op0 = N0.getOperand(0);
25273   SDValue Op1 = N1.getOperand(0);
25274   if (ShAmt0.getOpcode() == ISD::SUB) {
25275     Opc = X86ISD::SHRD;
25276     std::swap(Op0, Op1);
25277     std::swap(ShAmt0, ShAmt1);
25278   }
25279
25280   unsigned Bits = VT.getSizeInBits();
25281   if (ShAmt1.getOpcode() == ISD::SUB) {
25282     SDValue Sum = ShAmt1.getOperand(0);
25283     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25284       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25285       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25286         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25287       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25288         return DAG.getNode(Opc, DL, VT,
25289                            Op0, Op1,
25290                            DAG.getNode(ISD::TRUNCATE, DL,
25291                                        MVT::i8, ShAmt0));
25292     }
25293   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25294     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25295     if (ShAmt0C &&
25296         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25297       return DAG.getNode(Opc, DL, VT,
25298                          N0.getOperand(0), N1.getOperand(0),
25299                          DAG.getNode(ISD::TRUNCATE, DL,
25300                                        MVT::i8, ShAmt0));
25301   }
25302
25303   return SDValue();
25304 }
25305
25306 // Generate NEG and CMOV for integer abs.
25307 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25308   EVT VT = N->getValueType(0);
25309
25310   // Since X86 does not have CMOV for 8-bit integer, we don't convert
25311   // 8-bit integer abs to NEG and CMOV.
25312   if (VT.isInteger() && VT.getSizeInBits() == 8)
25313     return SDValue();
25314
25315   SDValue N0 = N->getOperand(0);
25316   SDValue N1 = N->getOperand(1);
25317   SDLoc DL(N);
25318
25319   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25320   // and change it to SUB and CMOV.
25321   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25322       N0.getOpcode() == ISD::ADD &&
25323       N0.getOperand(1) == N1 &&
25324       N1.getOpcode() == ISD::SRA &&
25325       N1.getOperand(0) == N0.getOperand(0))
25326     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25327       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25328         // Generate SUB & CMOV.
25329         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25330                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
25331
25332         SDValue Ops[] = { N0.getOperand(0), Neg,
25333                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25334                           SDValue(Neg.getNode(), 1) };
25335         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25336       }
25337   return SDValue();
25338 }
25339
25340 // Try to turn tests against the signbit in the form of:
25341 //   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25342 // into:
25343 //   SETGT(X, -1)
25344 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25345   // This is only worth doing if the output type is i8.
25346   if (N->getValueType(0) != MVT::i8)
25347     return SDValue();
25348
25349   SDValue N0 = N->getOperand(0);
25350   SDValue N1 = N->getOperand(1);
25351
25352   // We should be performing an xor against a truncated shift.
25353   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25354     return SDValue();
25355
25356   // Make sure we are performing an xor against one.
25357   if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
25358     return SDValue();
25359
25360   // SetCC on x86 zero extends so only act on this if it's a logical shift.
25361   SDValue Shift = N0.getOperand(0);
25362   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25363     return SDValue();
25364
25365   // Make sure we are truncating from one of i16, i32 or i64.
25366   EVT ShiftTy = Shift.getValueType();
25367   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25368     return SDValue();
25369
25370   // Make sure the shift amount extracts the sign bit.
25371   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25372       Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25373     return SDValue();
25374
25375   // Create a greater-than comparison against -1.
25376   // N.B. Using SETGE against 0 works but we want a canonical looking
25377   // comparison, using SETGT matches up with what TranslateX86CC.
25378   SDLoc DL(N);
25379   SDValue ShiftOp = Shift.getOperand(0);
25380   EVT ShiftOpTy = ShiftOp.getValueType();
25381   SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25382                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25383   return Cond;
25384 }
25385
25386 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25387                                  TargetLowering::DAGCombinerInfo &DCI,
25388                                  const X86Subtarget *Subtarget) {
25389   if (DCI.isBeforeLegalizeOps())
25390     return SDValue();
25391
25392   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25393     return RV;
25394
25395   if (Subtarget->hasCMov())
25396     if (SDValue RV = performIntegerAbsCombine(N, DAG))
25397       return RV;
25398
25399   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25400     return FPLogic;
25401
25402   return SDValue();
25403 }
25404
25405 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
25406 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
25407 /// X86ISD::AVG instruction.
25408 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
25409                                 const X86Subtarget *Subtarget, SDLoc DL) {
25410   if (!VT.isVector() || !VT.isSimple())
25411     return SDValue();
25412   EVT InVT = In.getValueType();
25413   unsigned NumElems = VT.getVectorNumElements();
25414
25415   EVT ScalarVT = VT.getVectorElementType();
25416   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
25417         isPowerOf2_32(NumElems)))
25418     return SDValue();
25419
25420   // InScalarVT is the intermediate type in AVG pattern and it should be greater
25421   // than the original input type (i8/i16).
25422   EVT InScalarVT = InVT.getVectorElementType();
25423   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
25424     return SDValue();
25425
25426   if (Subtarget->hasAVX512()) {
25427     if (VT.getSizeInBits() > 512)
25428       return SDValue();
25429   } else if (Subtarget->hasAVX2()) {
25430     if (VT.getSizeInBits() > 256)
25431       return SDValue();
25432   } else {
25433     if (VT.getSizeInBits() > 128)
25434       return SDValue();
25435   }
25436
25437   // Detect the following pattern:
25438   //
25439   //   %1 = zext <N x i8> %a to <N x i32>
25440   //   %2 = zext <N x i8> %b to <N x i32>
25441   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
25442   //   %4 = add nuw nsw <N x i32> %3, %2
25443   //   %5 = lshr <N x i32> %N, <i32 1 x N>
25444   //   %6 = trunc <N x i32> %5 to <N x i8>
25445   //
25446   // In AVX512, the last instruction can also be a trunc store.
25447
25448   if (In.getOpcode() != ISD::SRL)
25449     return SDValue();
25450
25451   // A lambda checking the given SDValue is a constant vector and each element
25452   // is in the range [Min, Max].
25453   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
25454     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
25455     if (!BV || !BV->isConstant())
25456       return false;
25457     for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
25458       ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
25459       if (!C)
25460         return false;
25461       uint64_t Val = C->getZExtValue();
25462       if (Val < Min || Val > Max)
25463         return false;
25464     }
25465     return true;
25466   };
25467
25468   // Check if each element of the vector is left-shifted by one.
25469   auto LHS = In.getOperand(0);
25470   auto RHS = In.getOperand(1);
25471   if (!IsConstVectorInRange(RHS, 1, 1))
25472     return SDValue();
25473   if (LHS.getOpcode() != ISD::ADD)
25474     return SDValue();
25475
25476   // Detect a pattern of a + b + 1 where the order doesn't matter.
25477   SDValue Operands[3];
25478   Operands[0] = LHS.getOperand(0);
25479   Operands[1] = LHS.getOperand(1);
25480
25481   // Take care of the case when one of the operands is a constant vector whose
25482   // element is in the range [1, 256].
25483   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
25484       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
25485       Operands[0].getOperand(0).getValueType() == VT) {
25486     // The pattern is detected. Subtract one from the constant vector, then
25487     // demote it and emit X86ISD::AVG instruction.
25488     SDValue One = DAG.getConstant(1, DL, InScalarVT);
25489     SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
25490                                SmallVector<SDValue, 8>(NumElems, One));
25491     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
25492     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
25493     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
25494                        Operands[1]);
25495   }
25496
25497   if (Operands[0].getOpcode() == ISD::ADD)
25498     std::swap(Operands[0], Operands[1]);
25499   else if (Operands[1].getOpcode() != ISD::ADD)
25500     return SDValue();
25501   Operands[2] = Operands[1].getOperand(0);
25502   Operands[1] = Operands[1].getOperand(1);
25503
25504   // Now we have three operands of two additions. Check that one of them is a
25505   // constant vector with ones, and the other two are promoted from i8/i16.
25506   for (int i = 0; i < 3; ++i) {
25507     if (!IsConstVectorInRange(Operands[i], 1, 1))
25508       continue;
25509     std::swap(Operands[i], Operands[2]);
25510
25511     // Check if Operands[0] and Operands[1] are results of type promotion.
25512     for (int j = 0; j < 2; ++j)
25513       if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
25514           Operands[j].getOperand(0).getValueType() != VT)
25515         return SDValue();
25516
25517     // The pattern is detected, emit X86ISD::AVG instruction.
25518     return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
25519                        Operands[1].getOperand(0));
25520   }
25521
25522   return SDValue();
25523 }
25524
25525 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
25526                                       const X86Subtarget *Subtarget) {
25527   return detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG, Subtarget,
25528                           SDLoc(N));
25529 }
25530
25531 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25532 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25533                                   TargetLowering::DAGCombinerInfo &DCI,
25534                                   const X86Subtarget *Subtarget) {
25535   LoadSDNode *Ld = cast<LoadSDNode>(N);
25536   EVT RegVT = Ld->getValueType(0);
25537   EVT MemVT = Ld->getMemoryVT();
25538   SDLoc dl(Ld);
25539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25540
25541   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25542   // into two 16-byte operations.
25543   ISD::LoadExtType Ext = Ld->getExtensionType();
25544   bool Fast;
25545   unsigned AddressSpace = Ld->getAddressSpace();
25546   unsigned Alignment = Ld->getAlignment();
25547   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25548       Ext == ISD::NON_EXTLOAD &&
25549       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25550                              AddressSpace, Alignment, &Fast) && !Fast) {
25551     unsigned NumElems = RegVT.getVectorNumElements();
25552     if (NumElems < 2)
25553       return SDValue();
25554
25555     SDValue Ptr = Ld->getBasePtr();
25556     SDValue Increment =
25557         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25558
25559     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25560                                   NumElems/2);
25561     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25562                                 Ld->getPointerInfo(), Ld->isVolatile(),
25563                                 Ld->isNonTemporal(), Ld->isInvariant(),
25564                                 Alignment);
25565     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25566     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25567                                 Ld->getPointerInfo(), Ld->isVolatile(),
25568                                 Ld->isNonTemporal(), Ld->isInvariant(),
25569                                 std::min(16U, Alignment));
25570     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25571                              Load1.getValue(1),
25572                              Load2.getValue(1));
25573
25574     SDValue NewVec = DAG.getUNDEF(RegVT);
25575     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25576     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25577     return DCI.CombineTo(N, NewVec, TF, true);
25578   }
25579
25580   return SDValue();
25581 }
25582
25583 /// PerformMLOADCombine - Resolve extending loads
25584 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25585                                    TargetLowering::DAGCombinerInfo &DCI,
25586                                    const X86Subtarget *Subtarget) {
25587   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25588   if (Mld->getExtensionType() != ISD::SEXTLOAD)
25589     return SDValue();
25590
25591   EVT VT = Mld->getValueType(0);
25592   unsigned NumElems = VT.getVectorNumElements();
25593   EVT LdVT = Mld->getMemoryVT();
25594   SDLoc dl(Mld);
25595
25596   assert(LdVT != VT && "Cannot extend to the same type");
25597   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25598   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25599   // From, To sizes and ElemCount must be pow of two
25600   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25601     "Unexpected size for extending masked load");
25602
25603   unsigned SizeRatio  = ToSz / FromSz;
25604   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25605
25606   // Create a type on which we perform the shuffle
25607   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25608           LdVT.getScalarType(), NumElems*SizeRatio);
25609   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25610
25611   // Convert Src0 value
25612   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25613   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25614     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25615     for (unsigned i = 0; i != NumElems; ++i)
25616       ShuffleVec[i] = i * SizeRatio;
25617
25618     // Can't shuffle using an illegal type.
25619     assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25620            "WideVecVT should be legal");
25621     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25622                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25623   }
25624   // Prepare the new mask
25625   SDValue NewMask;
25626   SDValue Mask = Mld->getMask();
25627   if (Mask.getValueType() == VT) {
25628     // Mask and original value have the same type
25629     NewMask = DAG.getBitcast(WideVecVT, Mask);
25630     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25631     for (unsigned i = 0; i != NumElems; ++i)
25632       ShuffleVec[i] = i * SizeRatio;
25633     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25634       ShuffleVec[i] = NumElems*SizeRatio;
25635     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25636                                    DAG.getConstant(0, dl, WideVecVT),
25637                                    &ShuffleVec[0]);
25638   }
25639   else {
25640     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25641     unsigned WidenNumElts = NumElems*SizeRatio;
25642     unsigned MaskNumElts = VT.getVectorNumElements();
25643     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25644                                      WidenNumElts);
25645
25646     unsigned NumConcat = WidenNumElts / MaskNumElts;
25647     SmallVector<SDValue, 16> Ops(NumConcat);
25648     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25649     Ops[0] = Mask;
25650     for (unsigned i = 1; i != NumConcat; ++i)
25651       Ops[i] = ZeroVal;
25652
25653     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25654   }
25655
25656   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25657                                      Mld->getBasePtr(), NewMask, WideSrc0,
25658                                      Mld->getMemoryVT(), Mld->getMemOperand(),
25659                                      ISD::NON_EXTLOAD);
25660   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25661   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25662 }
25663 /// PerformMSTORECombine - Resolve truncating stores
25664 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25665                                     const X86Subtarget *Subtarget) {
25666   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25667   if (!Mst->isTruncatingStore())
25668     return SDValue();
25669
25670   EVT VT = Mst->getValue().getValueType();
25671   unsigned NumElems = VT.getVectorNumElements();
25672   EVT StVT = Mst->getMemoryVT();
25673   SDLoc dl(Mst);
25674
25675   assert(StVT != VT && "Cannot truncate to the same type");
25676   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25677   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25678
25679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25680
25681   // The truncating store is legal in some cases. For example
25682   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25683   // are designated for truncate store.
25684   // In this case we don't need any further transformations.
25685   if (TLI.isTruncStoreLegal(VT, StVT))
25686     return SDValue();
25687
25688   // From, To sizes and ElemCount must be pow of two
25689   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25690     "Unexpected size for truncating masked store");
25691   // We are going to use the original vector elt for storing.
25692   // Accumulated smaller vector elements must be a multiple of the store size.
25693   assert (((NumElems * FromSz) % ToSz) == 0 &&
25694           "Unexpected ratio for truncating masked store");
25695
25696   unsigned SizeRatio  = FromSz / ToSz;
25697   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25698
25699   // Create a type on which we perform the shuffle
25700   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25701           StVT.getScalarType(), NumElems*SizeRatio);
25702
25703   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25704
25705   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25706   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25707   for (unsigned i = 0; i != NumElems; ++i)
25708     ShuffleVec[i] = i * SizeRatio;
25709
25710   // Can't shuffle using an illegal type.
25711   assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25712          "WideVecVT should be legal");
25713
25714   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25715                                         DAG.getUNDEF(WideVecVT),
25716                                         &ShuffleVec[0]);
25717
25718   SDValue NewMask;
25719   SDValue Mask = Mst->getMask();
25720   if (Mask.getValueType() == VT) {
25721     // Mask and original value have the same type
25722     NewMask = DAG.getBitcast(WideVecVT, Mask);
25723     for (unsigned i = 0; i != NumElems; ++i)
25724       ShuffleVec[i] = i * SizeRatio;
25725     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25726       ShuffleVec[i] = NumElems*SizeRatio;
25727     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25728                                    DAG.getConstant(0, dl, WideVecVT),
25729                                    &ShuffleVec[0]);
25730   }
25731   else {
25732     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25733     unsigned WidenNumElts = NumElems*SizeRatio;
25734     unsigned MaskNumElts = VT.getVectorNumElements();
25735     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
25736                                      WidenNumElts);
25737
25738     unsigned NumConcat = WidenNumElts / MaskNumElts;
25739     SmallVector<SDValue, 16> Ops(NumConcat);
25740     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25741     Ops[0] = Mask;
25742     for (unsigned i = 1; i != NumConcat; ++i)
25743       Ops[i] = ZeroVal;
25744
25745     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25746   }
25747
25748   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
25749                             NewMask, StVT, Mst->getMemOperand(), false);
25750 }
25751 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25752 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25753                                    const X86Subtarget *Subtarget) {
25754   StoreSDNode *St = cast<StoreSDNode>(N);
25755   EVT VT = St->getValue().getValueType();
25756   EVT StVT = St->getMemoryVT();
25757   SDLoc dl(St);
25758   SDValue StoredVal = St->getOperand(1);
25759   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25760
25761   // If we are saving a concatenation of two XMM registers and 32-byte stores
25762   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25763   bool Fast;
25764   unsigned AddressSpace = St->getAddressSpace();
25765   unsigned Alignment = St->getAlignment();
25766   if (VT.is256BitVector() && StVT == VT &&
25767       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25768                              AddressSpace, Alignment, &Fast) && !Fast) {
25769     unsigned NumElems = VT.getVectorNumElements();
25770     if (NumElems < 2)
25771       return SDValue();
25772
25773     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25774     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25775
25776     SDValue Stride =
25777         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25778     SDValue Ptr0 = St->getBasePtr();
25779     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25780
25781     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25782                                 St->getPointerInfo(), St->isVolatile(),
25783                                 St->isNonTemporal(), Alignment);
25784     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25785                                 St->getPointerInfo(), St->isVolatile(),
25786                                 St->isNonTemporal(),
25787                                 std::min(16U, Alignment));
25788     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25789   }
25790
25791   // Optimize trunc store (of multiple scalars) to shuffle and store.
25792   // First, pack all of the elements in one place. Next, store to memory
25793   // in fewer chunks.
25794   if (St->isTruncatingStore() && VT.isVector()) {
25795     // Check if we can detect an AVG pattern from the truncation. If yes,
25796     // replace the trunc store by a normal store with the result of X86ISD::AVG
25797     // instruction.
25798     SDValue Avg =
25799         detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
25800     if (Avg.getNode())
25801       return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
25802                           St->getPointerInfo(), St->isVolatile(),
25803                           St->isNonTemporal(), St->getAlignment());
25804
25805     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25806     unsigned NumElems = VT.getVectorNumElements();
25807     assert(StVT != VT && "Cannot truncate to the same type");
25808     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25809     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25810
25811     // The truncating store is legal in some cases. For example
25812     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25813     // are designated for truncate store.
25814     // In this case we don't need any further transformations.
25815     if (TLI.isTruncStoreLegal(VT, StVT))
25816       return SDValue();
25817
25818     // From, To sizes and ElemCount must be pow of two
25819     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25820     // We are going to use the original vector elt for storing.
25821     // Accumulated smaller vector elements must be a multiple of the store size.
25822     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25823
25824     unsigned SizeRatio  = FromSz / ToSz;
25825
25826     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25827
25828     // Create a type on which we perform the shuffle
25829     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25830             StVT.getScalarType(), NumElems*SizeRatio);
25831
25832     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25833
25834     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25835     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25836     for (unsigned i = 0; i != NumElems; ++i)
25837       ShuffleVec[i] = i * SizeRatio;
25838
25839     // Can't shuffle using an illegal type.
25840     if (!TLI.isTypeLegal(WideVecVT))
25841       return SDValue();
25842
25843     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25844                                          DAG.getUNDEF(WideVecVT),
25845                                          &ShuffleVec[0]);
25846     // At this point all of the data is stored at the bottom of the
25847     // register. We now need to save it to mem.
25848
25849     // Find the largest store unit
25850     MVT StoreType = MVT::i8;
25851     for (MVT Tp : MVT::integer_valuetypes()) {
25852       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25853         StoreType = Tp;
25854     }
25855
25856     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25857     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25858         (64 <= NumElems * ToSz))
25859       StoreType = MVT::f64;
25860
25861     // Bitcast the original vector into a vector of store-size units
25862     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25863             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25864     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25865     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25866     SmallVector<SDValue, 8> Chains;
25867     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25868                                         TLI.getPointerTy(DAG.getDataLayout()));
25869     SDValue Ptr = St->getBasePtr();
25870
25871     // Perform one or more big stores into memory.
25872     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25873       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25874                                    StoreType, ShuffWide,
25875                                    DAG.getIntPtrConstant(i, dl));
25876       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25877                                 St->getPointerInfo(), St->isVolatile(),
25878                                 St->isNonTemporal(), St->getAlignment());
25879       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25880       Chains.push_back(Ch);
25881     }
25882
25883     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25884   }
25885
25886   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
25887   // the FP state in cases where an emms may be missing.
25888   // A preferable solution to the general problem is to figure out the right
25889   // places to insert EMMS.  This qualifies as a quick hack.
25890
25891   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25892   if (VT.getSizeInBits() != 64)
25893     return SDValue();
25894
25895   const Function *F = DAG.getMachineFunction().getFunction();
25896   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25897   bool F64IsLegal =
25898       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25899   if ((VT.isVector() ||
25900        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25901       isa<LoadSDNode>(St->getValue()) &&
25902       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25903       St->getChain().hasOneUse() && !St->isVolatile()) {
25904     SDNode* LdVal = St->getValue().getNode();
25905     LoadSDNode *Ld = nullptr;
25906     int TokenFactorIndex = -1;
25907     SmallVector<SDValue, 8> Ops;
25908     SDNode* ChainVal = St->getChain().getNode();
25909     // Must be a store of a load.  We currently handle two cases:  the load
25910     // is a direct child, and it's under an intervening TokenFactor.  It is
25911     // possible to dig deeper under nested TokenFactors.
25912     if (ChainVal == LdVal)
25913       Ld = cast<LoadSDNode>(St->getChain());
25914     else if (St->getValue().hasOneUse() &&
25915              ChainVal->getOpcode() == ISD::TokenFactor) {
25916       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25917         if (ChainVal->getOperand(i).getNode() == LdVal) {
25918           TokenFactorIndex = i;
25919           Ld = cast<LoadSDNode>(St->getValue());
25920         } else
25921           Ops.push_back(ChainVal->getOperand(i));
25922       }
25923     }
25924
25925     if (!Ld || !ISD::isNormalLoad(Ld))
25926       return SDValue();
25927
25928     // If this is not the MMX case, i.e. we are just turning i64 load/store
25929     // into f64 load/store, avoid the transformation if there are multiple
25930     // uses of the loaded value.
25931     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25932       return SDValue();
25933
25934     SDLoc LdDL(Ld);
25935     SDLoc StDL(N);
25936     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25937     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25938     // pair instead.
25939     if (Subtarget->is64Bit() || F64IsLegal) {
25940       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25941       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25942                                   Ld->getPointerInfo(), Ld->isVolatile(),
25943                                   Ld->isNonTemporal(), Ld->isInvariant(),
25944                                   Ld->getAlignment());
25945       SDValue NewChain = NewLd.getValue(1);
25946       if (TokenFactorIndex != -1) {
25947         Ops.push_back(NewChain);
25948         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25949       }
25950       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25951                           St->getPointerInfo(),
25952                           St->isVolatile(), St->isNonTemporal(),
25953                           St->getAlignment());
25954     }
25955
25956     // Otherwise, lower to two pairs of 32-bit loads / stores.
25957     SDValue LoAddr = Ld->getBasePtr();
25958     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25959                                  DAG.getConstant(4, LdDL, MVT::i32));
25960
25961     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25962                                Ld->getPointerInfo(),
25963                                Ld->isVolatile(), Ld->isNonTemporal(),
25964                                Ld->isInvariant(), Ld->getAlignment());
25965     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25966                                Ld->getPointerInfo().getWithOffset(4),
25967                                Ld->isVolatile(), Ld->isNonTemporal(),
25968                                Ld->isInvariant(),
25969                                MinAlign(Ld->getAlignment(), 4));
25970
25971     SDValue NewChain = LoLd.getValue(1);
25972     if (TokenFactorIndex != -1) {
25973       Ops.push_back(LoLd);
25974       Ops.push_back(HiLd);
25975       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25976     }
25977
25978     LoAddr = St->getBasePtr();
25979     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25980                          DAG.getConstant(4, StDL, MVT::i32));
25981
25982     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25983                                 St->getPointerInfo(),
25984                                 St->isVolatile(), St->isNonTemporal(),
25985                                 St->getAlignment());
25986     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25987                                 St->getPointerInfo().getWithOffset(4),
25988                                 St->isVolatile(),
25989                                 St->isNonTemporal(),
25990                                 MinAlign(St->getAlignment(), 4));
25991     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25992   }
25993
25994   // This is similar to the above case, but here we handle a scalar 64-bit
25995   // integer store that is extracted from a vector on a 32-bit target.
25996   // If we have SSE2, then we can treat it like a floating-point double
25997   // to get past legalization. The execution dependencies fixup pass will
25998   // choose the optimal machine instruction for the store if this really is
25999   // an integer or v2f32 rather than an f64.
26000   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26001       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26002     SDValue OldExtract = St->getOperand(1);
26003     SDValue ExtOp0 = OldExtract.getOperand(0);
26004     unsigned VecSize = ExtOp0.getValueSizeInBits();
26005     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26006     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26007     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26008                                      BitCast, OldExtract.getOperand(1));
26009     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26010                         St->getPointerInfo(), St->isVolatile(),
26011                         St->isNonTemporal(), St->getAlignment());
26012   }
26013
26014   return SDValue();
26015 }
26016
26017 /// Return 'true' if this vector operation is "horizontal"
26018 /// and return the operands for the horizontal operation in LHS and RHS.  A
26019 /// horizontal operation performs the binary operation on successive elements
26020 /// of its first operand, then on successive elements of its second operand,
26021 /// returning the resulting values in a vector.  For example, if
26022 ///   A = < float a0, float a1, float a2, float a3 >
26023 /// and
26024 ///   B = < float b0, float b1, float b2, float b3 >
26025 /// then the result of doing a horizontal operation on A and B is
26026 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26027 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26028 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26029 /// set to A, RHS to B, and the routine returns 'true'.
26030 /// Note that the binary operation should have the property that if one of the
26031 /// operands is UNDEF then the result is UNDEF.
26032 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26033   // Look for the following pattern: if
26034   //   A = < float a0, float a1, float a2, float a3 >
26035   //   B = < float b0, float b1, float b2, float b3 >
26036   // and
26037   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26038   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26039   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26040   // which is A horizontal-op B.
26041
26042   // At least one of the operands should be a vector shuffle.
26043   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26044       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26045     return false;
26046
26047   MVT VT = LHS.getSimpleValueType();
26048
26049   assert((VT.is128BitVector() || VT.is256BitVector()) &&
26050          "Unsupported vector type for horizontal add/sub");
26051
26052   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26053   // operate independently on 128-bit lanes.
26054   unsigned NumElts = VT.getVectorNumElements();
26055   unsigned NumLanes = VT.getSizeInBits()/128;
26056   unsigned NumLaneElts = NumElts / NumLanes;
26057   assert((NumLaneElts % 2 == 0) &&
26058          "Vector type should have an even number of elements in each lane");
26059   unsigned HalfLaneElts = NumLaneElts/2;
26060
26061   // View LHS in the form
26062   //   LHS = VECTOR_SHUFFLE A, B, LMask
26063   // If LHS is not a shuffle then pretend it is the shuffle
26064   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26065   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26066   // type VT.
26067   SDValue A, B;
26068   SmallVector<int, 16> LMask(NumElts);
26069   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26070     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26071       A = LHS.getOperand(0);
26072     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26073       B = LHS.getOperand(1);
26074     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26075     std::copy(Mask.begin(), Mask.end(), LMask.begin());
26076   } else {
26077     if (LHS.getOpcode() != ISD::UNDEF)
26078       A = LHS;
26079     for (unsigned i = 0; i != NumElts; ++i)
26080       LMask[i] = i;
26081   }
26082
26083   // Likewise, view RHS in the form
26084   //   RHS = VECTOR_SHUFFLE C, D, RMask
26085   SDValue C, D;
26086   SmallVector<int, 16> RMask(NumElts);
26087   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26088     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26089       C = RHS.getOperand(0);
26090     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26091       D = RHS.getOperand(1);
26092     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26093     std::copy(Mask.begin(), Mask.end(), RMask.begin());
26094   } else {
26095     if (RHS.getOpcode() != ISD::UNDEF)
26096       C = RHS;
26097     for (unsigned i = 0; i != NumElts; ++i)
26098       RMask[i] = i;
26099   }
26100
26101   // Check that the shuffles are both shuffling the same vectors.
26102   if (!(A == C && B == D) && !(A == D && B == C))
26103     return false;
26104
26105   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26106   if (!A.getNode() && !B.getNode())
26107     return false;
26108
26109   // If A and B occur in reverse order in RHS, then "swap" them (which means
26110   // rewriting the mask).
26111   if (A != C)
26112     ShuffleVectorSDNode::commuteMask(RMask);
26113
26114   // At this point LHS and RHS are equivalent to
26115   //   LHS = VECTOR_SHUFFLE A, B, LMask
26116   //   RHS = VECTOR_SHUFFLE A, B, RMask
26117   // Check that the masks correspond to performing a horizontal operation.
26118   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26119     for (unsigned i = 0; i != NumLaneElts; ++i) {
26120       int LIdx = LMask[i+l], RIdx = RMask[i+l];
26121
26122       // Ignore any UNDEF components.
26123       if (LIdx < 0 || RIdx < 0 ||
26124           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26125           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26126         continue;
26127
26128       // Check that successive elements are being operated on.  If not, this is
26129       // not a horizontal operation.
26130       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26131       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26132       if (!(LIdx == Index && RIdx == Index + 1) &&
26133           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26134         return false;
26135     }
26136   }
26137
26138   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26139   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26140   return true;
26141 }
26142
26143 /// Do target-specific dag combines on floating point adds.
26144 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26145                                   const X86Subtarget *Subtarget) {
26146   EVT VT = N->getValueType(0);
26147   SDValue LHS = N->getOperand(0);
26148   SDValue RHS = N->getOperand(1);
26149
26150   // Try to synthesize horizontal adds from adds of shuffles.
26151   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26152        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26153       isHorizontalBinOp(LHS, RHS, true))
26154     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26155   return SDValue();
26156 }
26157
26158 /// Do target-specific dag combines on floating point subs.
26159 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26160                                   const X86Subtarget *Subtarget) {
26161   EVT VT = N->getValueType(0);
26162   SDValue LHS = N->getOperand(0);
26163   SDValue RHS = N->getOperand(1);
26164
26165   // Try to synthesize horizontal subs from subs of shuffles.
26166   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26167        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26168       isHorizontalBinOp(LHS, RHS, false))
26169     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26170   return SDValue();
26171 }
26172
26173 /// Do target-specific dag combines on floating point negations.
26174 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26175                                   const X86Subtarget *Subtarget) {
26176   EVT VT = N->getValueType(0);
26177   SDValue Arg = N->getOperand(0);
26178
26179   // If we're negating a FMA node, then we can adjust the
26180   // instruction to include the extra negation.
26181   if (Arg.hasOneUse()) {
26182     switch (Arg.getOpcode()) {
26183       case X86ISD::FMADD:
26184         return DAG.getNode(X86ISD::FNMSUB, SDLoc(N), VT, Arg.getOperand(0),
26185                            Arg.getOperand(1), Arg.getOperand(2));
26186       case X86ISD::FMSUB:
26187         return DAG.getNode(X86ISD::FNMADD, SDLoc(N), VT, Arg.getOperand(0),
26188                            Arg.getOperand(1), Arg.getOperand(2));
26189       case X86ISD::FNMADD:
26190         return DAG.getNode(X86ISD::FMSUB, SDLoc(N), VT, Arg.getOperand(0),
26191                            Arg.getOperand(1), Arg.getOperand(2));
26192       case X86ISD::FNMSUB:
26193         return DAG.getNode(X86ISD::FMADD, SDLoc(N), VT, Arg.getOperand(0),
26194                            Arg.getOperand(1), Arg.getOperand(2));
26195     }
26196   }
26197   return SDValue();
26198 }
26199
26200 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
26201 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
26202                                  const X86Subtarget *Subtarget) {
26203   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
26204
26205   // F[X]OR(0.0, x) -> x
26206   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26207     if (C->getValueAPF().isPosZero())
26208       return N->getOperand(1);
26209
26210   // F[X]OR(x, 0.0) -> x
26211   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26212     if (C->getValueAPF().isPosZero())
26213       return N->getOperand(0);
26214
26215   EVT VT = N->getValueType(0);
26216   if (VT.is512BitVector() && !Subtarget->hasDQI()) {
26217     SDLoc dl(N);
26218     MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
26219     MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
26220
26221     SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
26222     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
26223     unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
26224     SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
26225     return  DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
26226   }
26227   return SDValue();
26228 }
26229
26230 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
26231 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
26232   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
26233
26234   // Only perform optimizations if UnsafeMath is used.
26235   if (!DAG.getTarget().Options.UnsafeFPMath)
26236     return SDValue();
26237
26238   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
26239   // into FMINC and FMAXC, which are Commutative operations.
26240   unsigned NewOp = 0;
26241   switch (N->getOpcode()) {
26242     default: llvm_unreachable("unknown opcode");
26243     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
26244     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
26245   }
26246
26247   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
26248                      N->getOperand(0), N->getOperand(1));
26249 }
26250
26251 /// Do target-specific dag combines on X86ISD::FAND nodes.
26252 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
26253   // FAND(0.0, x) -> 0.0
26254   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26255     if (C->getValueAPF().isPosZero())
26256       return N->getOperand(0);
26257
26258   // FAND(x, 0.0) -> 0.0
26259   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26260     if (C->getValueAPF().isPosZero())
26261       return N->getOperand(1);
26262
26263   return SDValue();
26264 }
26265
26266 /// Do target-specific dag combines on X86ISD::FANDN nodes
26267 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
26268   // FANDN(0.0, x) -> x
26269   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26270     if (C->getValueAPF().isPosZero())
26271       return N->getOperand(1);
26272
26273   // FANDN(x, 0.0) -> 0.0
26274   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26275     if (C->getValueAPF().isPosZero())
26276       return N->getOperand(1);
26277
26278   return SDValue();
26279 }
26280
26281 static SDValue PerformBTCombine(SDNode *N,
26282                                 SelectionDAG &DAG,
26283                                 TargetLowering::DAGCombinerInfo &DCI) {
26284   // BT ignores high bits in the bit index operand.
26285   SDValue Op1 = N->getOperand(1);
26286   if (Op1.hasOneUse()) {
26287     unsigned BitWidth = Op1.getValueSizeInBits();
26288     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
26289     APInt KnownZero, KnownOne;
26290     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
26291                                           !DCI.isBeforeLegalizeOps());
26292     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26293     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
26294         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
26295       DCI.CommitTargetLoweringOpt(TLO);
26296   }
26297   return SDValue();
26298 }
26299
26300 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
26301   SDValue Op = N->getOperand(0);
26302   if (Op.getOpcode() == ISD::BITCAST)
26303     Op = Op.getOperand(0);
26304   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
26305   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
26306       VT.getVectorElementType().getSizeInBits() ==
26307       OpVT.getVectorElementType().getSizeInBits()) {
26308     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
26309   }
26310   return SDValue();
26311 }
26312
26313 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
26314                                                const X86Subtarget *Subtarget) {
26315   EVT VT = N->getValueType(0);
26316   if (!VT.isVector())
26317     return SDValue();
26318
26319   SDValue N0 = N->getOperand(0);
26320   SDValue N1 = N->getOperand(1);
26321   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
26322   SDLoc dl(N);
26323
26324   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
26325   // both SSE and AVX2 since there is no sign-extended shift right
26326   // operation on a vector with 64-bit elements.
26327   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
26328   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
26329   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
26330       N0.getOpcode() == ISD::SIGN_EXTEND)) {
26331     SDValue N00 = N0.getOperand(0);
26332
26333     // EXTLOAD has a better solution on AVX2,
26334     // it may be replaced with X86ISD::VSEXT node.
26335     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
26336       if (!ISD::isNormalLoad(N00.getNode()))
26337         return SDValue();
26338
26339     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
26340         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
26341                                   N00, N1);
26342       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
26343     }
26344   }
26345   return SDValue();
26346 }
26347
26348 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
26349 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
26350 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
26351 /// eliminate extend, add, and shift instructions.
26352 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
26353                                        const X86Subtarget *Subtarget) {
26354   // TODO: This should be valid for other integer types.
26355   EVT VT = Sext->getValueType(0);
26356   if (VT != MVT::i64)
26357     return SDValue();
26358
26359   // We need an 'add nsw' feeding into the 'sext'.
26360   SDValue Add = Sext->getOperand(0);
26361   if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
26362     return SDValue();
26363
26364   // Having a constant operand to the 'add' ensures that we are not increasing
26365   // the instruction count because the constant is extended for free below.
26366   // A constant operand can also become the displacement field of an LEA.
26367   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
26368   if (!AddOp1)
26369     return SDValue();
26370
26371   // Don't make the 'add' bigger if there's no hope of combining it with some
26372   // other 'add' or 'shl' instruction.
26373   // TODO: It may be profitable to generate simpler LEA instructions in place
26374   // of single 'add' instructions, but the cost model for selecting an LEA
26375   // currently has a high threshold.
26376   bool HasLEAPotential = false;
26377   for (auto *User : Sext->uses()) {
26378     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
26379       HasLEAPotential = true;
26380       break;
26381     }
26382   }
26383   if (!HasLEAPotential)
26384     return SDValue();
26385
26386   // Everything looks good, so pull the 'sext' ahead of the 'add'.
26387   int64_t AddConstant = AddOp1->getSExtValue();
26388   SDValue AddOp0 = Add.getOperand(0);
26389   SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
26390   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
26391
26392   // The wider add is guaranteed to not wrap because both operands are
26393   // sign-extended.
26394   SDNodeFlags Flags;
26395   Flags.setNoSignedWrap(true);
26396   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
26397 }
26398
26399 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
26400                                   TargetLowering::DAGCombinerInfo &DCI,
26401                                   const X86Subtarget *Subtarget) {
26402   SDValue N0 = N->getOperand(0);
26403   EVT VT = N->getValueType(0);
26404   EVT SVT = VT.getScalarType();
26405   EVT InVT = N0.getValueType();
26406   EVT InSVT = InVT.getScalarType();
26407   SDLoc DL(N);
26408
26409   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
26410   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
26411   // This exposes the sext to the sdivrem lowering, so that it directly extends
26412   // from AH (which we otherwise need to do contortions to access).
26413   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
26414       InVT == MVT::i8 && VT == MVT::i32) {
26415     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26416     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
26417                             N0.getOperand(0), N0.getOperand(1));
26418     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26419     return R.getValue(1);
26420   }
26421
26422   if (!DCI.isBeforeLegalizeOps()) {
26423     if (InVT == MVT::i1) {
26424       SDValue Zero = DAG.getConstant(0, DL, VT);
26425       SDValue AllOnes =
26426         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
26427       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
26428     }
26429     return SDValue();
26430   }
26431
26432   if (VT.isVector() && Subtarget->hasSSE2()) {
26433     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
26434       EVT InVT = N.getValueType();
26435       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
26436                                    Size / InVT.getScalarSizeInBits());
26437       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
26438                                     DAG.getUNDEF(InVT));
26439       Opnds[0] = N;
26440       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
26441     };
26442
26443     // If target-size is less than 128-bits, extend to a type that would extend
26444     // to 128 bits, extend that and extract the original target vector.
26445     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
26446         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26447         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26448       unsigned Scale = 128 / VT.getSizeInBits();
26449       EVT ExVT =
26450           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
26451       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
26452       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
26453       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
26454                          DAG.getIntPtrConstant(0, DL));
26455     }
26456
26457     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
26458     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
26459     if (VT.getSizeInBits() == 128 &&
26460         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26461         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26462       SDValue ExOp = ExtendVecSize(DL, N0, 128);
26463       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
26464     }
26465
26466     // On pre-AVX2 targets, split into 128-bit nodes of
26467     // ISD::SIGN_EXTEND_VECTOR_INREG.
26468     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
26469         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26470         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26471       unsigned NumVecs = VT.getSizeInBits() / 128;
26472       unsigned NumSubElts = 128 / SVT.getSizeInBits();
26473       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
26474       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
26475
26476       SmallVector<SDValue, 8> Opnds;
26477       for (unsigned i = 0, Offset = 0; i != NumVecs;
26478            ++i, Offset += NumSubElts) {
26479         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
26480                                      DAG.getIntPtrConstant(Offset, DL));
26481         SrcVec = ExtendVecSize(DL, SrcVec, 128);
26482         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26483         Opnds.push_back(SrcVec);
26484       }
26485       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26486     }
26487   }
26488
26489   if (Subtarget->hasAVX() && VT.is256BitVector())
26490     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26491       return R;
26492
26493   if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26494     return NewAdd;
26495
26496   return SDValue();
26497 }
26498
26499 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26500                                  const X86Subtarget* Subtarget) {
26501   SDLoc dl(N);
26502   EVT VT = N->getValueType(0);
26503
26504   // Let legalize expand this if it isn't a legal type yet.
26505   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26506     return SDValue();
26507
26508   EVT ScalarVT = VT.getScalarType();
26509   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
26510       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
26511        !Subtarget->hasAVX512()))
26512     return SDValue();
26513
26514   SDValue A = N->getOperand(0);
26515   SDValue B = N->getOperand(1);
26516   SDValue C = N->getOperand(2);
26517
26518   bool NegA = (A.getOpcode() == ISD::FNEG);
26519   bool NegB = (B.getOpcode() == ISD::FNEG);
26520   bool NegC = (C.getOpcode() == ISD::FNEG);
26521
26522   // Negative multiplication when NegA xor NegB
26523   bool NegMul = (NegA != NegB);
26524   if (NegA)
26525     A = A.getOperand(0);
26526   if (NegB)
26527     B = B.getOperand(0);
26528   if (NegC)
26529     C = C.getOperand(0);
26530
26531   unsigned Opcode;
26532   if (!NegMul)
26533     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26534   else
26535     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26536
26537   return DAG.getNode(Opcode, dl, VT, A, B, C);
26538 }
26539
26540 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26541                                   TargetLowering::DAGCombinerInfo &DCI,
26542                                   const X86Subtarget *Subtarget) {
26543   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
26544   //           (and (i32 x86isd::setcc_carry), 1)
26545   // This eliminates the zext. This transformation is necessary because
26546   // ISD::SETCC is always legalized to i8.
26547   SDLoc dl(N);
26548   SDValue N0 = N->getOperand(0);
26549   EVT VT = N->getValueType(0);
26550
26551   if (N0.getOpcode() == ISD::AND &&
26552       N0.hasOneUse() &&
26553       N0.getOperand(0).hasOneUse()) {
26554     SDValue N00 = N0.getOperand(0);
26555     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26556       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
26557       if (!C || C->getZExtValue() != 1)
26558         return SDValue();
26559       return DAG.getNode(ISD::AND, dl, VT,
26560                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26561                                      N00.getOperand(0), N00.getOperand(1)),
26562                          DAG.getConstant(1, dl, VT));
26563     }
26564   }
26565
26566   if (N0.getOpcode() == ISD::TRUNCATE &&
26567       N0.hasOneUse() &&
26568       N0.getOperand(0).hasOneUse()) {
26569     SDValue N00 = N0.getOperand(0);
26570     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26571       return DAG.getNode(ISD::AND, dl, VT,
26572                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26573                                      N00.getOperand(0), N00.getOperand(1)),
26574                          DAG.getConstant(1, dl, VT));
26575     }
26576   }
26577
26578   if (VT.is256BitVector())
26579     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26580       return R;
26581
26582   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26583   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26584   // This exposes the zext to the udivrem lowering, so that it directly extends
26585   // from AH (which we otherwise need to do contortions to access).
26586   if (N0.getOpcode() == ISD::UDIVREM &&
26587       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26588       (VT == MVT::i32 || VT == MVT::i64)) {
26589     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26590     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26591                             N0.getOperand(0), N0.getOperand(1));
26592     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26593     return R.getValue(1);
26594   }
26595
26596   return SDValue();
26597 }
26598
26599 // Optimize x == -y --> x+y == 0
26600 //          x != -y --> x+y != 0
26601 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26602                                       const X86Subtarget* Subtarget) {
26603   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26604   SDValue LHS = N->getOperand(0);
26605   SDValue RHS = N->getOperand(1);
26606   EVT VT = N->getValueType(0);
26607   SDLoc DL(N);
26608
26609   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26610     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
26611       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
26612         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26613                                    LHS.getOperand(1));
26614         return DAG.getSetCC(DL, N->getValueType(0), addV,
26615                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26616       }
26617   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26618     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
26619       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
26620         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26621                                    RHS.getOperand(1));
26622         return DAG.getSetCC(DL, N->getValueType(0), addV,
26623                             DAG.getConstant(0, DL, addV.getValueType()), CC);
26624       }
26625
26626   if (VT.getScalarType() == MVT::i1 &&
26627       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26628     bool IsSEXT0 =
26629         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26630         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26631     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26632
26633     if (!IsSEXT0 || !IsVZero1) {
26634       // Swap the operands and update the condition code.
26635       std::swap(LHS, RHS);
26636       CC = ISD::getSetCCSwappedOperands(CC);
26637
26638       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26639                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26640       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26641     }
26642
26643     if (IsSEXT0 && IsVZero1) {
26644       assert(VT == LHS.getOperand(0).getValueType() &&
26645              "Uexpected operand type");
26646       if (CC == ISD::SETGT)
26647         return DAG.getConstant(0, DL, VT);
26648       if (CC == ISD::SETLE)
26649         return DAG.getConstant(1, DL, VT);
26650       if (CC == ISD::SETEQ || CC == ISD::SETGE)
26651         return DAG.getNOT(DL, LHS.getOperand(0), VT);
26652
26653       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26654              "Unexpected condition code!");
26655       return LHS.getOperand(0);
26656     }
26657   }
26658
26659   return SDValue();
26660 }
26661
26662 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26663   SDValue V0 = N->getOperand(0);
26664   SDValue V1 = N->getOperand(1);
26665   SDLoc DL(N);
26666   EVT VT = N->getValueType(0);
26667
26668   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26669   // operands and changing the mask to 1. This saves us a bunch of
26670   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26671   // x86InstrInfo knows how to commute this back after instruction selection
26672   // if it would help register allocation.
26673
26674   // TODO: If optimizing for size or a processor that doesn't suffer from
26675   // partial register update stalls, this should be transformed into a MOVSD
26676   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26677
26678   if (VT == MVT::v2f64)
26679     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26680       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26681         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26682         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26683       }
26684
26685   return SDValue();
26686 }
26687
26688 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26689 // as "sbb reg,reg", since it can be extended without zext and produces
26690 // an all-ones bit which is more useful than 0/1 in some cases.
26691 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26692                                MVT VT) {
26693   if (VT == MVT::i8)
26694     return DAG.getNode(ISD::AND, DL, VT,
26695                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26696                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
26697                                    EFLAGS),
26698                        DAG.getConstant(1, DL, VT));
26699   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26700   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26701                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26702                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
26703                                  EFLAGS));
26704 }
26705
26706 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26707 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26708                                    TargetLowering::DAGCombinerInfo &DCI,
26709                                    const X86Subtarget *Subtarget) {
26710   SDLoc DL(N);
26711   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26712   SDValue EFLAGS = N->getOperand(1);
26713
26714   if (CC == X86::COND_A) {
26715     // Try to convert COND_A into COND_B in an attempt to facilitate
26716     // materializing "setb reg".
26717     //
26718     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26719     // cannot take an immediate as its first operand.
26720     //
26721     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26722         EFLAGS.getValueType().isInteger() &&
26723         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26724       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26725                                    EFLAGS.getNode()->getVTList(),
26726                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26727       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26728       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26729     }
26730   }
26731
26732   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26733   // a zext and produces an all-ones bit which is more useful than 0/1 in some
26734   // cases.
26735   if (CC == X86::COND_B)
26736     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26737
26738   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26739     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26740     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26741   }
26742
26743   return SDValue();
26744 }
26745
26746 // Optimize branch condition evaluation.
26747 //
26748 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26749                                     TargetLowering::DAGCombinerInfo &DCI,
26750                                     const X86Subtarget *Subtarget) {
26751   SDLoc DL(N);
26752   SDValue Chain = N->getOperand(0);
26753   SDValue Dest = N->getOperand(1);
26754   SDValue EFLAGS = N->getOperand(3);
26755   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26756
26757   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26758     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26759     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26760                        Flags);
26761   }
26762
26763   return SDValue();
26764 }
26765
26766 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26767                                                          SelectionDAG &DAG) {
26768   // Take advantage of vector comparisons producing 0 or -1 in each lane to
26769   // optimize away operation when it's from a constant.
26770   //
26771   // The general transformation is:
26772   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26773   //       AND(VECTOR_CMP(x,y), constant2)
26774   //    constant2 = UNARYOP(constant)
26775
26776   // Early exit if this isn't a vector operation, the operand of the
26777   // unary operation isn't a bitwise AND, or if the sizes of the operations
26778   // aren't the same.
26779   EVT VT = N->getValueType(0);
26780   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
26781       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
26782       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
26783     return SDValue();
26784
26785   // Now check that the other operand of the AND is a constant. We could
26786   // make the transformation for non-constant splats as well, but it's unclear
26787   // that would be a benefit as it would not eliminate any operations, just
26788   // perform one more step in scalar code before moving to the vector unit.
26789   if (BuildVectorSDNode *BV =
26790           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
26791     // Bail out if the vector isn't a constant.
26792     if (!BV->isConstant())
26793       return SDValue();
26794
26795     // Everything checks out. Build up the new and improved node.
26796     SDLoc DL(N);
26797     EVT IntVT = BV->getValueType(0);
26798     // Create a new constant of the appropriate type for the transformed
26799     // DAG.
26800     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
26801     // The AND node needs bitcasts to/from an integer vector type around it.
26802     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
26803     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
26804                                  N->getOperand(0)->getOperand(0), MaskConst);
26805     SDValue Res = DAG.getBitcast(VT, NewAnd);
26806     return Res;
26807   }
26808
26809   return SDValue();
26810 }
26811
26812 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26813                                         const X86Subtarget *Subtarget) {
26814   SDValue Op0 = N->getOperand(0);
26815   EVT VT = N->getValueType(0);
26816   EVT InVT = Op0.getValueType();
26817   EVT InSVT = InVT.getScalarType();
26818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26819
26820   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
26821   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
26822   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26823     SDLoc dl(N);
26824     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26825                                  InVT.getVectorNumElements());
26826     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
26827
26828     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
26829       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
26830
26831     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26832   }
26833
26834   return SDValue();
26835 }
26836
26837 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26838                                         const X86Subtarget *Subtarget) {
26839   // First try to optimize away the conversion entirely when it's
26840   // conditionally from a constant. Vectors only.
26841   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26842     return Res;
26843
26844   // Now move on to more general possibilities.
26845   SDValue Op0 = N->getOperand(0);
26846   EVT VT = N->getValueType(0);
26847   EVT InVT = Op0.getValueType();
26848   EVT InSVT = InVT.getScalarType();
26849
26850   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26851   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26852   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26853     SDLoc dl(N);
26854     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26855                                  InVT.getVectorNumElements());
26856     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26857     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26858   }
26859
26860   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26861   // a 32-bit target where SSE doesn't support i64->FP operations.
26862   if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
26863     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26864     EVT LdVT = Ld->getValueType(0);
26865
26866     // This transformation is not supported if the result type is f16
26867     if (VT == MVT::f16)
26868       return SDValue();
26869
26870     if (!Ld->isVolatile() && !VT.isVector() &&
26871         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26872         !Subtarget->is64Bit() && LdVT == MVT::i64) {
26873       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26874           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26875       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26876       return FILDChain;
26877     }
26878   }
26879   return SDValue();
26880 }
26881
26882 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26883 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26884                                  X86TargetLowering::DAGCombinerInfo &DCI) {
26885   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26886   // the result is either zero or one (depending on the input carry bit).
26887   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26888   if (X86::isZeroNode(N->getOperand(0)) &&
26889       X86::isZeroNode(N->getOperand(1)) &&
26890       // We don't have a good way to replace an EFLAGS use, so only do this when
26891       // dead right now.
26892       SDValue(N, 1).use_empty()) {
26893     SDLoc DL(N);
26894     EVT VT = N->getValueType(0);
26895     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26896     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26897                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26898                                            DAG.getConstant(X86::COND_B, DL,
26899                                                            MVT::i8),
26900                                            N->getOperand(2)),
26901                                DAG.getConstant(1, DL, VT));
26902     return DCI.CombineTo(N, Res1, CarryOut);
26903   }
26904
26905   return SDValue();
26906 }
26907
26908 // fold (add Y, (sete  X, 0)) -> adc  0, Y
26909 //      (add Y, (setne X, 0)) -> sbb -1, Y
26910 //      (sub (sete  X, 0), Y) -> sbb  0, Y
26911 //      (sub (setne X, 0), Y) -> adc -1, Y
26912 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26913   SDLoc DL(N);
26914
26915   // Look through ZExts.
26916   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26917   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26918     return SDValue();
26919
26920   SDValue SetCC = Ext.getOperand(0);
26921   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26922     return SDValue();
26923
26924   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26925   if (CC != X86::COND_E && CC != X86::COND_NE)
26926     return SDValue();
26927
26928   SDValue Cmp = SetCC.getOperand(1);
26929   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26930       !X86::isZeroNode(Cmp.getOperand(1)) ||
26931       !Cmp.getOperand(0).getValueType().isInteger())
26932     return SDValue();
26933
26934   SDValue CmpOp0 = Cmp.getOperand(0);
26935   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26936                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
26937
26938   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26939   if (CC == X86::COND_NE)
26940     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26941                        DL, OtherVal.getValueType(), OtherVal,
26942                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26943                        NewCmp);
26944   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26945                      DL, OtherVal.getValueType(), OtherVal,
26946                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26947 }
26948
26949 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26950 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26951                                  const X86Subtarget *Subtarget) {
26952   EVT VT = N->getValueType(0);
26953   SDValue Op0 = N->getOperand(0);
26954   SDValue Op1 = N->getOperand(1);
26955
26956   // Try to synthesize horizontal adds from adds of shuffles.
26957   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26958        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26959       isHorizontalBinOp(Op0, Op1, true))
26960     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26961
26962   return OptimizeConditionalInDecrement(N, DAG);
26963 }
26964
26965 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26966                                  const X86Subtarget *Subtarget) {
26967   SDValue Op0 = N->getOperand(0);
26968   SDValue Op1 = N->getOperand(1);
26969
26970   // X86 can't encode an immediate LHS of a sub. See if we can push the
26971   // negation into a preceding instruction.
26972   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26973     // If the RHS of the sub is a XOR with one use and a constant, invert the
26974     // immediate. Then add one to the LHS of the sub so we can turn
26975     // X-Y -> X+~Y+1, saving one register.
26976     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26977         isa<ConstantSDNode>(Op1.getOperand(1))) {
26978       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26979       EVT VT = Op0.getValueType();
26980       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26981                                    Op1.getOperand(0),
26982                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
26983       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26984                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26985     }
26986   }
26987
26988   // Try to synthesize horizontal adds from adds of shuffles.
26989   EVT VT = N->getValueType(0);
26990   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26991        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26992       isHorizontalBinOp(Op0, Op1, true))
26993     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26994
26995   return OptimizeConditionalInDecrement(N, DAG);
26996 }
26997
26998 /// performVZEXTCombine - Performs build vector combines
26999 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27000                                    TargetLowering::DAGCombinerInfo &DCI,
27001                                    const X86Subtarget *Subtarget) {
27002   SDLoc DL(N);
27003   MVT VT = N->getSimpleValueType(0);
27004   SDValue Op = N->getOperand(0);
27005   MVT OpVT = Op.getSimpleValueType();
27006   MVT OpEltVT = OpVT.getVectorElementType();
27007   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27008
27009   // (vzext (bitcast (vzext (x)) -> (vzext x)
27010   SDValue V = Op;
27011   while (V.getOpcode() == ISD::BITCAST)
27012     V = V.getOperand(0);
27013
27014   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27015     MVT InnerVT = V.getSimpleValueType();
27016     MVT InnerEltVT = InnerVT.getVectorElementType();
27017
27018     // If the element sizes match exactly, we can just do one larger vzext. This
27019     // is always an exact type match as vzext operates on integer types.
27020     if (OpEltVT == InnerEltVT) {
27021       assert(OpVT == InnerVT && "Types must match for vzext!");
27022       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27023     }
27024
27025     // The only other way we can combine them is if only a single element of the
27026     // inner vzext is used in the input to the outer vzext.
27027     if (InnerEltVT.getSizeInBits() < InputBits)
27028       return SDValue();
27029
27030     // In this case, the inner vzext is completely dead because we're going to
27031     // only look at bits inside of the low element. Just do the outer vzext on
27032     // a bitcast of the input to the inner.
27033     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27034   }
27035
27036   // Check if we can bypass extracting and re-inserting an element of an input
27037   // vector. Essentially:
27038   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27039   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27040       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27041       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27042     SDValue ExtractedV = V.getOperand(0);
27043     SDValue OrigV = ExtractedV.getOperand(0);
27044     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
27045       if (ExtractIdx->getZExtValue() == 0) {
27046         MVT OrigVT = OrigV.getSimpleValueType();
27047         // Extract a subvector if necessary...
27048         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27049           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27050           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27051                                     OrigVT.getVectorNumElements() / Ratio);
27052           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27053                               DAG.getIntPtrConstant(0, DL));
27054         }
27055         Op = DAG.getBitcast(OpVT, OrigV);
27056         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27057       }
27058   }
27059
27060   return SDValue();
27061 }
27062
27063 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27064                                              DAGCombinerInfo &DCI) const {
27065   SelectionDAG &DAG = DCI.DAG;
27066   switch (N->getOpcode()) {
27067   default: break;
27068   case ISD::EXTRACT_VECTOR_ELT:
27069     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27070   case ISD::VSELECT:
27071   case ISD::SELECT:
27072   case X86ISD::SHRUNKBLEND:
27073     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27074   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG, Subtarget);
27075   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27076   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
27077   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
27078   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
27079   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
27080   case ISD::SHL:
27081   case ISD::SRA:
27082   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
27083   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
27084   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
27085   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
27086   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
27087   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27088   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
27089   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
27090   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27091   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27092   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
27093   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
27094   case ISD::FNEG:           return PerformFNEGCombine(N, DAG, Subtarget);
27095   case ISD::TRUNCATE:       return PerformTRUNCATECombine(N, DAG, Subtarget);
27096   case X86ISD::FXOR:
27097   case X86ISD::FOR:         return PerformFORCombine(N, DAG, Subtarget);
27098   case X86ISD::FMIN:
27099   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
27100   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
27101   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
27102   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
27103   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
27104   case ISD::ANY_EXTEND:
27105   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
27106   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
27107   case ISD::SIGN_EXTEND_INREG:
27108     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27109   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
27110   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27111   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27112   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
27113   case X86ISD::SHUFP:       // Handle all target specific shuffles
27114   case X86ISD::PALIGNR:
27115   case X86ISD::UNPCKH:
27116   case X86ISD::UNPCKL:
27117   case X86ISD::MOVHLPS:
27118   case X86ISD::MOVLHPS:
27119   case X86ISD::PSHUFB:
27120   case X86ISD::PSHUFD:
27121   case X86ISD::PSHUFHW:
27122   case X86ISD::PSHUFLW:
27123   case X86ISD::MOVSS:
27124   case X86ISD::MOVSD:
27125   case X86ISD::VPERMILPI:
27126   case X86ISD::VPERM2X128:
27127   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27128   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
27129   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
27130   }
27131
27132   return SDValue();
27133 }
27134
27135 /// isTypeDesirableForOp - Return true if the target has native support for
27136 /// the specified value type and it is 'desirable' to use the type for the
27137 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27138 /// instruction encodings are longer and some i16 instructions are slow.
27139 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
27140   if (!isTypeLegal(VT))
27141     return false;
27142   if (VT != MVT::i16)
27143     return true;
27144
27145   switch (Opc) {
27146   default:
27147     return true;
27148   case ISD::LOAD:
27149   case ISD::SIGN_EXTEND:
27150   case ISD::ZERO_EXTEND:
27151   case ISD::ANY_EXTEND:
27152   case ISD::SHL:
27153   case ISD::SRL:
27154   case ISD::SUB:
27155   case ISD::ADD:
27156   case ISD::MUL:
27157   case ISD::AND:
27158   case ISD::OR:
27159   case ISD::XOR:
27160     return false;
27161   }
27162 }
27163
27164 /// IsDesirableToPromoteOp - This method query the target whether it is
27165 /// beneficial for dag combiner to promote the specified node. If true, it
27166 /// should return the desired promotion type by reference.
27167 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
27168   EVT VT = Op.getValueType();
27169   if (VT != MVT::i16)
27170     return false;
27171
27172   bool Promote = false;
27173   bool Commute = false;
27174   switch (Op.getOpcode()) {
27175   default: break;
27176   case ISD::LOAD: {
27177     LoadSDNode *LD = cast<LoadSDNode>(Op);
27178     // If the non-extending load has a single use and it's not live out, then it
27179     // might be folded.
27180     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
27181                                                      Op.hasOneUse()*/) {
27182       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
27183              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
27184         // The only case where we'd want to promote LOAD (rather then it being
27185         // promoted as an operand is when it's only use is liveout.
27186         if (UI->getOpcode() != ISD::CopyToReg)
27187           return false;
27188       }
27189     }
27190     Promote = true;
27191     break;
27192   }
27193   case ISD::SIGN_EXTEND:
27194   case ISD::ZERO_EXTEND:
27195   case ISD::ANY_EXTEND:
27196     Promote = true;
27197     break;
27198   case ISD::SHL:
27199   case ISD::SRL: {
27200     SDValue N0 = Op.getOperand(0);
27201     // Look out for (store (shl (load), x)).
27202     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
27203       return false;
27204     Promote = true;
27205     break;
27206   }
27207   case ISD::ADD:
27208   case ISD::MUL:
27209   case ISD::AND:
27210   case ISD::OR:
27211   case ISD::XOR:
27212     Commute = true;
27213     // fallthrough
27214   case ISD::SUB: {
27215     SDValue N0 = Op.getOperand(0);
27216     SDValue N1 = Op.getOperand(1);
27217     if (!Commute && MayFoldLoad(N1))
27218       return false;
27219     // Avoid disabling potential load folding opportunities.
27220     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
27221       return false;
27222     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
27223       return false;
27224     Promote = true;
27225   }
27226   }
27227
27228   PVT = MVT::i32;
27229   return Promote;
27230 }
27231
27232 //===----------------------------------------------------------------------===//
27233 //                           X86 Inline Assembly Support
27234 //===----------------------------------------------------------------------===//
27235
27236 // Helper to match a string separated by whitespace.
27237 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
27238   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
27239
27240   for (StringRef Piece : Pieces) {
27241     if (!S.startswith(Piece)) // Check if the piece matches.
27242       return false;
27243
27244     S = S.substr(Piece.size());
27245     StringRef::size_type Pos = S.find_first_not_of(" \t");
27246     if (Pos == 0) // We matched a prefix.
27247       return false;
27248
27249     S = S.substr(Pos);
27250   }
27251
27252   return S.empty();
27253 }
27254
27255 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
27256
27257   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
27258     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
27259         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
27260         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
27261
27262       if (AsmPieces.size() == 3)
27263         return true;
27264       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
27265         return true;
27266     }
27267   }
27268   return false;
27269 }
27270
27271 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
27272   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
27273
27274   std::string AsmStr = IA->getAsmString();
27275
27276   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
27277   if (!Ty || Ty->getBitWidth() % 16 != 0)
27278     return false;
27279
27280   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
27281   SmallVector<StringRef, 4> AsmPieces;
27282   SplitString(AsmStr, AsmPieces, ";\n");
27283
27284   switch (AsmPieces.size()) {
27285   default: return false;
27286   case 1:
27287     // FIXME: this should verify that we are targeting a 486 or better.  If not,
27288     // we will turn this bswap into something that will be lowered to logical
27289     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
27290     // lower so don't worry about this.
27291     // bswap $0
27292     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
27293         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
27294         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
27295         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
27296         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
27297         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
27298       // No need to check constraints, nothing other than the equivalent of
27299       // "=r,0" would be valid here.
27300       return IntrinsicLowering::LowerToByteSwap(CI);
27301     }
27302
27303     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
27304     if (CI->getType()->isIntegerTy(16) &&
27305         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27306         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
27307          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
27308       AsmPieces.clear();
27309       StringRef ConstraintsStr = IA->getConstraintString();
27310       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27311       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27312       if (clobbersFlagRegisters(AsmPieces))
27313         return IntrinsicLowering::LowerToByteSwap(CI);
27314     }
27315     break;
27316   case 3:
27317     if (CI->getType()->isIntegerTy(32) &&
27318         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27319         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
27320         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
27321         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
27322       AsmPieces.clear();
27323       StringRef ConstraintsStr = IA->getConstraintString();
27324       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27325       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27326       if (clobbersFlagRegisters(AsmPieces))
27327         return IntrinsicLowering::LowerToByteSwap(CI);
27328     }
27329
27330     if (CI->getType()->isIntegerTy(64)) {
27331       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
27332       if (Constraints.size() >= 2 &&
27333           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
27334           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
27335         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
27336         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
27337             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
27338             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
27339           return IntrinsicLowering::LowerToByteSwap(CI);
27340       }
27341     }
27342     break;
27343   }
27344   return false;
27345 }
27346
27347 /// getConstraintType - Given a constraint letter, return the type of
27348 /// constraint it is for this target.
27349 X86TargetLowering::ConstraintType
27350 X86TargetLowering::getConstraintType(StringRef Constraint) const {
27351   if (Constraint.size() == 1) {
27352     switch (Constraint[0]) {
27353     case 'R':
27354     case 'q':
27355     case 'Q':
27356     case 'f':
27357     case 't':
27358     case 'u':
27359     case 'y':
27360     case 'x':
27361     case 'Y':
27362     case 'l':
27363       return C_RegisterClass;
27364     case 'a':
27365     case 'b':
27366     case 'c':
27367     case 'd':
27368     case 'S':
27369     case 'D':
27370     case 'A':
27371       return C_Register;
27372     case 'I':
27373     case 'J':
27374     case 'K':
27375     case 'L':
27376     case 'M':
27377     case 'N':
27378     case 'G':
27379     case 'C':
27380     case 'e':
27381     case 'Z':
27382       return C_Other;
27383     default:
27384       break;
27385     }
27386   }
27387   return TargetLowering::getConstraintType(Constraint);
27388 }
27389
27390 /// Examine constraint type and operand type and determine a weight value.
27391 /// This object must already have been set up with the operand type
27392 /// and the current alternative constraint selected.
27393 TargetLowering::ConstraintWeight
27394   X86TargetLowering::getSingleConstraintMatchWeight(
27395     AsmOperandInfo &info, const char *constraint) const {
27396   ConstraintWeight weight = CW_Invalid;
27397   Value *CallOperandVal = info.CallOperandVal;
27398     // If we don't have a value, we can't do a match,
27399     // but allow it at the lowest weight.
27400   if (!CallOperandVal)
27401     return CW_Default;
27402   Type *type = CallOperandVal->getType();
27403   // Look at the constraint type.
27404   switch (*constraint) {
27405   default:
27406     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
27407   case 'R':
27408   case 'q':
27409   case 'Q':
27410   case 'a':
27411   case 'b':
27412   case 'c':
27413   case 'd':
27414   case 'S':
27415   case 'D':
27416   case 'A':
27417     if (CallOperandVal->getType()->isIntegerTy())
27418       weight = CW_SpecificReg;
27419     break;
27420   case 'f':
27421   case 't':
27422   case 'u':
27423     if (type->isFloatingPointTy())
27424       weight = CW_SpecificReg;
27425     break;
27426   case 'y':
27427     if (type->isX86_MMXTy() && Subtarget->hasMMX())
27428       weight = CW_SpecificReg;
27429     break;
27430   case 'x':
27431   case 'Y':
27432     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27433         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27434       weight = CW_Register;
27435     break;
27436   case 'I':
27437     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27438       if (C->getZExtValue() <= 31)
27439         weight = CW_Constant;
27440     }
27441     break;
27442   case 'J':
27443     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27444       if (C->getZExtValue() <= 63)
27445         weight = CW_Constant;
27446     }
27447     break;
27448   case 'K':
27449     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27450       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27451         weight = CW_Constant;
27452     }
27453     break;
27454   case 'L':
27455     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27456       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27457         weight = CW_Constant;
27458     }
27459     break;
27460   case 'M':
27461     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27462       if (C->getZExtValue() <= 3)
27463         weight = CW_Constant;
27464     }
27465     break;
27466   case 'N':
27467     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27468       if (C->getZExtValue() <= 0xff)
27469         weight = CW_Constant;
27470     }
27471     break;
27472   case 'G':
27473   case 'C':
27474     if (isa<ConstantFP>(CallOperandVal)) {
27475       weight = CW_Constant;
27476     }
27477     break;
27478   case 'e':
27479     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27480       if ((C->getSExtValue() >= -0x80000000LL) &&
27481           (C->getSExtValue() <= 0x7fffffffLL))
27482         weight = CW_Constant;
27483     }
27484     break;
27485   case 'Z':
27486     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27487       if (C->getZExtValue() <= 0xffffffff)
27488         weight = CW_Constant;
27489     }
27490     break;
27491   }
27492   return weight;
27493 }
27494
27495 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27496 /// with another that has more specific requirements based on the type of the
27497 /// corresponding operand.
27498 const char *X86TargetLowering::
27499 LowerXConstraint(EVT ConstraintVT) const {
27500   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27501   // 'f' like normal targets.
27502   if (ConstraintVT.isFloatingPoint()) {
27503     if (Subtarget->hasSSE2())
27504       return "Y";
27505     if (Subtarget->hasSSE1())
27506       return "x";
27507   }
27508
27509   return TargetLowering::LowerXConstraint(ConstraintVT);
27510 }
27511
27512 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27513 /// vector.  If it is invalid, don't add anything to Ops.
27514 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27515                                                      std::string &Constraint,
27516                                                      std::vector<SDValue>&Ops,
27517                                                      SelectionDAG &DAG) const {
27518   SDValue Result;
27519
27520   // Only support length 1 constraints for now.
27521   if (Constraint.length() > 1) return;
27522
27523   char ConstraintLetter = Constraint[0];
27524   switch (ConstraintLetter) {
27525   default: break;
27526   case 'I':
27527     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27528       if (C->getZExtValue() <= 31) {
27529         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27530                                        Op.getValueType());
27531         break;
27532       }
27533     }
27534     return;
27535   case 'J':
27536     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27537       if (C->getZExtValue() <= 63) {
27538         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27539                                        Op.getValueType());
27540         break;
27541       }
27542     }
27543     return;
27544   case 'K':
27545     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27546       if (isInt<8>(C->getSExtValue())) {
27547         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27548                                        Op.getValueType());
27549         break;
27550       }
27551     }
27552     return;
27553   case 'L':
27554     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27555       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27556           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27557         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27558                                        Op.getValueType());
27559         break;
27560       }
27561     }
27562     return;
27563   case 'M':
27564     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27565       if (C->getZExtValue() <= 3) {
27566         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27567                                        Op.getValueType());
27568         break;
27569       }
27570     }
27571     return;
27572   case 'N':
27573     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27574       if (C->getZExtValue() <= 255) {
27575         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27576                                        Op.getValueType());
27577         break;
27578       }
27579     }
27580     return;
27581   case 'O':
27582     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27583       if (C->getZExtValue() <= 127) {
27584         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27585                                        Op.getValueType());
27586         break;
27587       }
27588     }
27589     return;
27590   case 'e': {
27591     // 32-bit signed value
27592     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27593       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27594                                            C->getSExtValue())) {
27595         // Widen to 64 bits here to get it sign extended.
27596         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27597         break;
27598       }
27599     // FIXME gcc accepts some relocatable values here too, but only in certain
27600     // memory models; it's complicated.
27601     }
27602     return;
27603   }
27604   case 'Z': {
27605     // 32-bit unsigned value
27606     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27607       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27608                                            C->getZExtValue())) {
27609         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27610                                        Op.getValueType());
27611         break;
27612       }
27613     }
27614     // FIXME gcc accepts some relocatable values here too, but only in certain
27615     // memory models; it's complicated.
27616     return;
27617   }
27618   case 'i': {
27619     // Literal immediates are always ok.
27620     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27621       // Widen to 64 bits here to get it sign extended.
27622       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27623       break;
27624     }
27625
27626     // In any sort of PIC mode addresses need to be computed at runtime by
27627     // adding in a register or some sort of table lookup.  These can't
27628     // be used as immediates.
27629     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27630       return;
27631
27632     // If we are in non-pic codegen mode, we allow the address of a global (with
27633     // an optional displacement) to be used with 'i'.
27634     GlobalAddressSDNode *GA = nullptr;
27635     int64_t Offset = 0;
27636
27637     // Match either (GA), (GA+C), (GA+C1+C2), etc.
27638     while (1) {
27639       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27640         Offset += GA->getOffset();
27641         break;
27642       } else if (Op.getOpcode() == ISD::ADD) {
27643         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27644           Offset += C->getZExtValue();
27645           Op = Op.getOperand(0);
27646           continue;
27647         }
27648       } else if (Op.getOpcode() == ISD::SUB) {
27649         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27650           Offset += -C->getZExtValue();
27651           Op = Op.getOperand(0);
27652           continue;
27653         }
27654       }
27655
27656       // Otherwise, this isn't something we can handle, reject it.
27657       return;
27658     }
27659
27660     const GlobalValue *GV = GA->getGlobal();
27661     // If we require an extra load to get this address, as in PIC mode, we
27662     // can't accept it.
27663     if (isGlobalStubReference(
27664             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27665       return;
27666
27667     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27668                                         GA->getValueType(0), Offset);
27669     break;
27670   }
27671   }
27672
27673   if (Result.getNode()) {
27674     Ops.push_back(Result);
27675     return;
27676   }
27677   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27678 }
27679
27680 std::pair<unsigned, const TargetRegisterClass *>
27681 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27682                                                 StringRef Constraint,
27683                                                 MVT VT) const {
27684   // First, see if this is a constraint that directly corresponds to an LLVM
27685   // register class.
27686   if (Constraint.size() == 1) {
27687     // GCC Constraint Letters
27688     switch (Constraint[0]) {
27689     default: break;
27690       // TODO: Slight differences here in allocation order and leaving
27691       // RIP in the class. Do they matter any more here than they do
27692       // in the normal allocation?
27693     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27694       if (Subtarget->is64Bit()) {
27695         if (VT == MVT::i32 || VT == MVT::f32)
27696           return std::make_pair(0U, &X86::GR32RegClass);
27697         if (VT == MVT::i16)
27698           return std::make_pair(0U, &X86::GR16RegClass);
27699         if (VT == MVT::i8 || VT == MVT::i1)
27700           return std::make_pair(0U, &X86::GR8RegClass);
27701         if (VT == MVT::i64 || VT == MVT::f64)
27702           return std::make_pair(0U, &X86::GR64RegClass);
27703         break;
27704       }
27705       // 32-bit fallthrough
27706     case 'Q':   // Q_REGS
27707       if (VT == MVT::i32 || VT == MVT::f32)
27708         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27709       if (VT == MVT::i16)
27710         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27711       if (VT == MVT::i8 || VT == MVT::i1)
27712         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27713       if (VT == MVT::i64)
27714         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27715       break;
27716     case 'r':   // GENERAL_REGS
27717     case 'l':   // INDEX_REGS
27718       if (VT == MVT::i8 || VT == MVT::i1)
27719         return std::make_pair(0U, &X86::GR8RegClass);
27720       if (VT == MVT::i16)
27721         return std::make_pair(0U, &X86::GR16RegClass);
27722       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27723         return std::make_pair(0U, &X86::GR32RegClass);
27724       return std::make_pair(0U, &X86::GR64RegClass);
27725     case 'R':   // LEGACY_REGS
27726       if (VT == MVT::i8 || VT == MVT::i1)
27727         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27728       if (VT == MVT::i16)
27729         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27730       if (VT == MVT::i32 || !Subtarget->is64Bit())
27731         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27732       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27733     case 'f':  // FP Stack registers.
27734       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27735       // value to the correct fpstack register class.
27736       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27737         return std::make_pair(0U, &X86::RFP32RegClass);
27738       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27739         return std::make_pair(0U, &X86::RFP64RegClass);
27740       return std::make_pair(0U, &X86::RFP80RegClass);
27741     case 'y':   // MMX_REGS if MMX allowed.
27742       if (!Subtarget->hasMMX()) break;
27743       return std::make_pair(0U, &X86::VR64RegClass);
27744     case 'Y':   // SSE_REGS if SSE2 allowed
27745       if (!Subtarget->hasSSE2()) break;
27746       // FALL THROUGH.
27747     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27748       if (!Subtarget->hasSSE1()) break;
27749
27750       switch (VT.SimpleTy) {
27751       default: break;
27752       // Scalar SSE types.
27753       case MVT::f32:
27754       case MVT::i32:
27755         return std::make_pair(0U, &X86::FR32RegClass);
27756       case MVT::f64:
27757       case MVT::i64:
27758         return std::make_pair(0U, &X86::FR64RegClass);
27759       // Vector types.
27760       case MVT::v16i8:
27761       case MVT::v8i16:
27762       case MVT::v4i32:
27763       case MVT::v2i64:
27764       case MVT::v4f32:
27765       case MVT::v2f64:
27766         return std::make_pair(0U, &X86::VR128RegClass);
27767       // AVX types.
27768       case MVT::v32i8:
27769       case MVT::v16i16:
27770       case MVT::v8i32:
27771       case MVT::v4i64:
27772       case MVT::v8f32:
27773       case MVT::v4f64:
27774         return std::make_pair(0U, &X86::VR256RegClass);
27775       case MVT::v8f64:
27776       case MVT::v16f32:
27777       case MVT::v16i32:
27778       case MVT::v8i64:
27779         return std::make_pair(0U, &X86::VR512RegClass);
27780       }
27781       break;
27782     }
27783   }
27784
27785   // Use the default implementation in TargetLowering to convert the register
27786   // constraint into a member of a register class.
27787   std::pair<unsigned, const TargetRegisterClass*> Res;
27788   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
27789
27790   // Not found as a standard register?
27791   if (!Res.second) {
27792     // Map st(0) -> st(7) -> ST0
27793     if (Constraint.size() == 7 && Constraint[0] == '{' &&
27794         tolower(Constraint[1]) == 's' &&
27795         tolower(Constraint[2]) == 't' &&
27796         Constraint[3] == '(' &&
27797         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
27798         Constraint[5] == ')' &&
27799         Constraint[6] == '}') {
27800
27801       Res.first = X86::FP0+Constraint[4]-'0';
27802       Res.second = &X86::RFP80RegClass;
27803       return Res;
27804     }
27805
27806     // GCC allows "st(0)" to be called just plain "st".
27807     if (StringRef("{st}").equals_lower(Constraint)) {
27808       Res.first = X86::FP0;
27809       Res.second = &X86::RFP80RegClass;
27810       return Res;
27811     }
27812
27813     // flags -> EFLAGS
27814     if (StringRef("{flags}").equals_lower(Constraint)) {
27815       Res.first = X86::EFLAGS;
27816       Res.second = &X86::CCRRegClass;
27817       return Res;
27818     }
27819
27820     // 'A' means EAX + EDX.
27821     if (Constraint == "A") {
27822       Res.first = X86::EAX;
27823       Res.second = &X86::GR32_ADRegClass;
27824       return Res;
27825     }
27826     return Res;
27827   }
27828
27829   // Otherwise, check to see if this is a register class of the wrong value
27830   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27831   // turn into {ax},{dx}.
27832   // MVT::Other is used to specify clobber names.
27833   if (Res.second->hasType(VT) || VT == MVT::Other)
27834     return Res;   // Correct type already, nothing to do.
27835
27836   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27837   // return "eax". This should even work for things like getting 64bit integer
27838   // registers when given an f64 type.
27839   const TargetRegisterClass *Class = Res.second;
27840   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27841       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27842     unsigned Size = VT.getSizeInBits();
27843     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27844                                   : Size == 16 ? MVT::i16
27845                                   : Size == 32 ? MVT::i32
27846                                   : Size == 64 ? MVT::i64
27847                                   : MVT::Other;
27848     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27849     if (DestReg > 0) {
27850       Res.first = DestReg;
27851       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27852                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27853                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27854                  : &X86::GR64RegClass;
27855       assert(Res.second->contains(Res.first) && "Register in register class");
27856     } else {
27857       // No register found/type mismatch.
27858       Res.first = 0;
27859       Res.second = nullptr;
27860     }
27861   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27862              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27863              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27864              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27865              Class == &X86::VR512RegClass) {
27866     // Handle references to XMM physical registers that got mapped into the
27867     // wrong class.  This can happen with constraints like {xmm0} where the
27868     // target independent register mapper will just pick the first match it can
27869     // find, ignoring the required type.
27870
27871     if (VT == MVT::f32 || VT == MVT::i32)
27872       Res.second = &X86::FR32RegClass;
27873     else if (VT == MVT::f64 || VT == MVT::i64)
27874       Res.second = &X86::FR64RegClass;
27875     else if (X86::VR128RegClass.hasType(VT))
27876       Res.second = &X86::VR128RegClass;
27877     else if (X86::VR256RegClass.hasType(VT))
27878       Res.second = &X86::VR256RegClass;
27879     else if (X86::VR512RegClass.hasType(VT))
27880       Res.second = &X86::VR512RegClass;
27881     else {
27882       // Type mismatch and not a clobber: Return an error;
27883       Res.first = 0;
27884       Res.second = nullptr;
27885     }
27886   }
27887
27888   return Res;
27889 }
27890
27891 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27892                                             const AddrMode &AM, Type *Ty,
27893                                             unsigned AS) const {
27894   // Scaling factors are not free at all.
27895   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27896   // will take 2 allocations in the out of order engine instead of 1
27897   // for plain addressing mode, i.e. inst (reg1).
27898   // E.g.,
27899   // vaddps (%rsi,%drx), %ymm0, %ymm1
27900   // Requires two allocations (one for the load, one for the computation)
27901   // whereas:
27902   // vaddps (%rsi), %ymm0, %ymm1
27903   // Requires just 1 allocation, i.e., freeing allocations for other operations
27904   // and having less micro operations to execute.
27905   //
27906   // For some X86 architectures, this is even worse because for instance for
27907   // stores, the complex addressing mode forces the instruction to use the
27908   // "load" ports instead of the dedicated "store" port.
27909   // E.g., on Haswell:
27910   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27911   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27912   if (isLegalAddressingMode(DL, AM, Ty, AS))
27913     // Scale represents reg2 * scale, thus account for 1
27914     // as soon as we use a second register.
27915     return AM.Scale != 0;
27916   return -1;
27917 }
27918
27919 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27920   // Integer division on x86 is expensive. However, when aggressively optimizing
27921   // for code size, we prefer to use a div instruction, as it is usually smaller
27922   // than the alternative sequence.
27923   // The exception to this is vector division. Since x86 doesn't have vector
27924   // integer division, leaving the division as-is is a loss even in terms of
27925   // size, because it will have to be scalarized, while the alternative code
27926   // sequence can be performed in vector form.
27927   bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27928                                    Attribute::MinSize);
27929   return OptSize && !VT.isVector();
27930 }
27931
27932 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
27933        TargetLowering::ArgListTy& Args) const {
27934   // The MCU psABI requires some arguments to be passed in-register.
27935   // For regular calls, the inreg arguments are marked by the front-end.
27936   // However, for compiler generated library calls, we have to patch this
27937   // up here.
27938   if (!Subtarget->isTargetMCU() || !Args.size())
27939     return;
27940
27941   unsigned FreeRegs = 3;
27942   for (auto &Arg : Args) {
27943     // For library functions, we do not expect any fancy types.
27944     unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
27945     unsigned SizeInRegs = (Size + 31) / 32;
27946     if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
27947       continue;
27948
27949     Arg.isInReg = true;
27950     FreeRegs -= SizeInRegs;
27951     if (!FreeRegs)
27952       break;
27953   }
27954 }